diff --git a/bundle.json b/bundle.json index d2f531cf4cb28c6b6e9957904aa35d03de5266af..b0c965533cc7f43f8a787416156061815a64bb28 100644 --- a/bundle.json +++ b/bundle.json @@ -31,33 +31,36 @@ "ability_base", "ability_runtime", "access_token", + "app_file_service", "bounds_checking_function", "bundle_framework", - "common_event_service", "c_utils", + "common_event_service", "data_share", "dfs_service", "eventhandler", "hilog", "hisysevent", "hitrace", - "ipc", "init", + "ipc", + "liburing", + "libuv", "napi", - "samgr", - "app_file_service", + "node", + "openssl", "os_account", - "liburing" + "runtime_core", + "rust_libc", + "samgr" ], - "third_party": [ - "e2fsprogs", - "openssl" - ] + "third_party": [] }, "build": { "group_type": { "base_group": [], "fwk_group": [ + "//foundation/filemanagement/file_api/interfaces/kits/js:ani_file_api", "//foundation/filemanagement/file_api/interfaces/kits/js:build_kits_js", "//foundation/filemanagement/file_api/interfaces/kits/ts/streamrw:streamrw_packages", "//foundation/filemanagement/file_api/interfaces/kits/ts/streamhash:streamhash_packages", @@ -112,6 +115,15 @@ "header_base": "//foundation/filemanagement/file_api/interfaces/kits/rust/include" } }, + { + "name": "//foundation/filemanagement/file_api/utils/filemgmt_libfs:filemgmt_libfs", + "header": { + "header_files": [ + "filemgmt_libfs.h" + ], + "header_base": "//foundation/filemanagement/file_api/utils/filemgmt_libfs/include" + } + }, { "name": "//foundation/filemanagement/file_api/utils/filemgmt_libn:filemgmt_libn", "header": { @@ -200,7 +212,7 @@ } ], "test": [ - "//foundation/filemanagement/file_api/interfaces/test/unittest:unittest" + "//foundation/filemanagement/file_api/interfaces/test/unittest:file_api_unittest" ] } } diff --git a/file_api.gni b/file_api.gni index 9e0d343959a8481bdc616b84e6cffb6aa26335e7..518d718c8dd63ce7aa73b31e6c4b18e3c16dea22 100644 --- a/file_api.gni +++ b/file_api.gni @@ -1,4 +1,4 @@ -# Copyright (c) 2022 Huawei Device Co., Ltd. +# Copyright (c) 2022-2025 Huawei Device Co., Ltd. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at @@ -11,12 +11,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -aafwk_kits_path = "//foundation/ability/ability_runtime/frameworks/native" -aafwk_path = "${aafwk_kits_path}/frameworks/kits" -arkui_napi_path = "//foundation/arkui/napi" file_api_path = "//foundation/filemanagement/file_api" -filemanagement_service_path = "//foundation/filemanagement/dfs_service/services" -hiviewdfx_hilog_path = "//base/hiviewdfx/hilog" src_path = "${file_api_path}/interfaces/kits/js/src" utils_path = "${file_api_path}/utils" diff --git a/interfaces/kits/c/environment/BUILD.gn b/interfaces/kits/c/environment/BUILD.gn index 2e3ce4ccbbf02af331cffa3f00dd3a60410eebef..758b5c01e90e6a3d6ec9c65e6b74df3ccc56e563 100644 --- a/interfaces/kits/c/environment/BUILD.gn +++ b/interfaces/kits/c/environment/BUILD.gn @@ -1,4 +1,4 @@ -# Copyright (C) 2024 Huawei Device Co., Ltd. +# Copyright (C) 2024-2025 Huawei Device Co., Ltd. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at @@ -33,7 +33,10 @@ ohos_shared_library("ohenvironment") { cfi_cross_dso = true debug = false } - include_dirs = [ "./" ] + include_dirs = [ + "./", + "../common/", + ] sources = [ "./environment.c" ] deps = [ "${file_api_path}/interfaces/kits/native:environment_native" ] diff --git a/interfaces/kits/c/environment/environment.c b/interfaces/kits/c/environment/environment.c index c7a6d2e96bf307af17208af7fa08fc9408563c52..509e945181ede4feebb64a46264d291b4b5387d9 100644 --- a/interfaces/kits/c/environment/environment.c +++ b/interfaces/kits/c/environment/environment.c @@ -1,5 +1,5 @@ /* - * Copyright (c) 2024 Huawei Device Co., Ltd. + * Copyright (c) 2024-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -18,7 +18,7 @@ #include #include "environment_native.h" -#include "../common/error_code.h" +#include "error_code.h" int OH_Environment_GetUserDownloadDir(char **result) { diff --git a/interfaces/kits/c/fileio/BUILD.gn b/interfaces/kits/c/fileio/BUILD.gn index 716f9e7c36388defb279e394d51e1b90e4c9cdb1..5a98cb0d1b98101099f09b8888cc4bedb622ccab 100644 --- a/interfaces/kits/c/fileio/BUILD.gn +++ b/interfaces/kits/c/fileio/BUILD.gn @@ -1,4 +1,4 @@ -# Copyright (C) 2024 Huawei Device Co., Ltd. +# Copyright (C) 2024-2025 Huawei Device Co., Ltd. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at @@ -34,7 +34,10 @@ ohos_shared_library("ohfileio") { "-fvisibility-inlines-hidden", "-Oz", ] - include_dirs = [ "./" ] + include_dirs = [ + "./", + "../common/", + ] sources = [ "./fileio.c" ] deps = [ "${file_api_path}/interfaces/kits/native:fileio_native" ] diff --git a/interfaces/kits/c/fileio/fileio.c b/interfaces/kits/c/fileio/fileio.c index 4004cf64624e9a89d1cbcff6365d836e31ed79c1..71904b4af2f96ab41ae8761f20e73225aada5b88 100644 --- a/interfaces/kits/c/fileio/fileio.c +++ b/interfaces/kits/c/fileio/fileio.c @@ -1,5 +1,5 @@ /* - * Copyright (c) 2024 Huawei Device Co., Ltd. + * Copyright (c) 2024-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -16,8 +16,8 @@ #include +#include "error_code.h" #include "fileio_native.h" -#include "../common/error_code.h" __attribute__((visibility("default"))) int OH_FileIO_GetFileLocation(char *uri, int uriLength, int *location) { diff --git a/interfaces/kits/cj/BUILD.gn b/interfaces/kits/cj/BUILD.gn index 3c36daad0e48172790776e48b8cd8cc0f45f5d9b..1a9cc0b52003c63b20c4147d6ec8b1bc4d2a30e2 100644 --- a/interfaces/kits/cj/BUILD.gn +++ b/interfaces/kits/cj/BUILD.gn @@ -15,50 +15,6 @@ import("//build/ohos.gni") import("//foundation/filemanagement/file_api/file_api.gni") ohos_shared_library("cj_file_fs_ffi") { - sanitize = { - integer_overflow = true - ubsan = true - boundary_sanitize = true - cfi = true - cfi_cross_dso = true - debug = false - } - - defines = [] - cflags = [ - "-fvisibility=hidden", - "-fdata-sections", - "-ffunction-sections", - "-Oz", - ] - cflags_cc = [ - "-fvisibility-inlines-hidden", - "-Oz", - ] - if (is_mingw || is_mac || is_linux) { - defines += [ "PREVIEW" ] - } - - if (current_os == "ohos" && current_cpu == "x86_64") { - defines += [ "SIMULATOR" ] - } - if (is_ohos) { - defines += [ "OHOS_PLATFORM" ] - if (use_musl && !is_asan) { - defines += [ "HOOK_ENABLE" ] - } - } else if (is_mingw) { - defines += [ "WINDOWS_PLATFORM" ] - cflags_cc += [ "-std=c++17" ] - } else if (is_mac) { - defines += [ "MAC_PLATFORM" ] - } else if (is_linux) { - defines += [ "LINUX_PLATFORM" ] - cflags_cc += [ "-std=c++17" ] - } else if (is_arkui_x && target_os == "ios") { - defines += [ "IOS_PLATFORM" ] - } - include_dirs = [ "${src_path}/common", "${src_path}/common/file_helper", @@ -78,84 +34,101 @@ ohos_shared_library("cj_file_fs_ffi") { "${file_api_path}/interfaces/kits/rust/include", ] - if (!defined(defines)) { - defines = [] - } + sources = [ + "../js/src/common/file_helper/fd_guard.cpp", + "../js/src/mod_fs/class_file/file_n_exporter.cpp", + "../js/src/mod_fs/class_stream/stream_n_exporter.cpp", + "../js/src/mod_fs/common_func.cpp", + "src/copy.cpp", + "src/copy_dir.cpp", + "src/copy_file.cpp", + "src/fdatasync.cpp", + "src/file_ffi.cpp", + "src/file_fs_ffi.cpp", + "src/file_fs_impl.cpp", + "src/file_impl.cpp", + "src/fsync.cpp", + "src/list_file.cpp", + "src/lseek.cpp", + "src/mkdtemp.cpp", + "src/move_file.cpp", + "src/randomAccessFile_impl.cpp", + "src/readerIterator_impl.cpp", + "src/stat_ffi.cpp", + "src/stat_impl.cpp", + "src/stream_ffi.cpp", + "src/stream_impl.cpp", + "src/symlink.cpp", + "src/task_signal_impl.cpp", + "src/translistener.cpp", + "src/uni_error.cpp", + "src/utils.cpp", + "src/watcher_impl.cpp", + "src/xattr.cpp", + "src/xattr_ffi.cpp", + ] + deps = [ + "${file_api_path}/interfaces/kits/js:build_kits_js", + "${file_api_path}/interfaces/kits/js:fs", + "${file_api_path}/interfaces/kits/native:remote_uri_native", + "${file_api_path}/interfaces/kits/native:task_signal_native", + "${file_api_path}/interfaces/kits/rust:rust_file", + "${utils_path}/filemgmt_libhilog:filemgmt_libhilog", + "${utils_path}/filemgmt_libn:filemgmt_libn", + ] + + cflags_cc = [ "-std=c++17" ] use_exceptions = true + if (use_mingw_win) { + defines = [ "WIN_PLATFORM" ] + } + if (use_mac) { + defines = [ "IOS_PLATFORM" ] + } + + external_deps = [ + "ability_base:zuri", + "ability_runtime:ability_manager", + "ability_runtime:abilitykit_native", + "access_token:libtokenid_sdk", + "app_file_service:fileuri_native", + "bounds_checking_function:libsec_shared", + "bundle_framework:appexecfwk_base", + "bundle_framework:appexecfwk_core", + "c_utils:utils", + "data_share:datashare_common", + "data_share:datashare_consumer", + "dfs_service:distributed_file_daemon_kit_inner", + "hilog:libhilog", + "ipc:ipc_core", + "napi:ace_napi", + "napi:cj_bind_ffi", + "napi:cj_bind_native", + "samgr:samgr_proxy", + ] - if (product_name != "ohos-sdk") { - deps = [ - "${file_api_path}/interfaces/kits/js:build_kits_js", - "${file_api_path}/interfaces/kits/js:fs", - "${file_api_path}/interfaces/kits/native:remote_uri_native", - "${file_api_path}/interfaces/kits/native:task_signal_native", - "${file_api_path}/interfaces/kits/rust:rust_file", - "${utils_path}/filemgmt_libhilog:filemgmt_libhilog", - "${utils_path}/filemgmt_libn:filemgmt_libn", + if (!use_mingw_win && !use_mac) { + cflags = [ + "-fvisibility=hidden", + "-fdata-sections", + "-ffunction-sections", + "-Oz", ] - external_deps = [ - "ability_base:zuri", - "ability_runtime:ability_manager", - "ability_runtime:abilitykit_native", - "access_token:libtokenid_sdk", - "app_file_service:fileuri_native", - "bounds_checking_function:libsec_shared", - "bundle_framework:appexecfwk_base", - "bundle_framework:appexecfwk_core", - "c_utils:utils", - "data_share:datashare_common", - "data_share:datashare_consumer", - "dfs_service:distributed_file_daemon_kit_inner", - "hilog:libhilog", - "ipc:ipc_core", - "napi:ace_napi", - "napi:cj_bind_ffi", - "napi:cj_bind_native", - "samgr:samgr_proxy", + cflags_cc += [ + "-fvisibility-inlines-hidden", + "-Oz", ] - sources = [ - "../js/src/common/file_helper/fd_guard.cpp", - "../js/src/mod_fs/class_file/file_n_exporter.cpp", - "../js/src/mod_fs/class_stream/stream_n_exporter.cpp", - "../js/src/mod_fs/common_func.cpp", - "src/copy.cpp", - "src/copy_dir.cpp", - "src/copy_file.cpp", - "src/fdatasync.cpp", - "src/file_ffi.cpp", - "src/file_fs_ffi.cpp", - "src/file_fs_impl.cpp", - "src/file_impl.cpp", - "src/fsync.cpp", - "src/list_file.cpp", - "src/lseek.cpp", - "src/mkdtemp.cpp", - "src/move_file.cpp", - "src/randomAccessFile_impl.cpp", - "src/readerIterator_impl.cpp", - "src/stat_ffi.cpp", - "src/stream_ffi.cpp", - "src/stream_impl.cpp", - "src/symlink.cpp", - "src/task_signal_impl.cpp", - "src/translistener.cpp", - "src/uni_error.cpp", - "src/utils.cpp", - "src/watcher_impl.cpp", - ] - } else { - defines += [ "PREVIEWER" ] - sources = [ "src/file_fs_mock.cpp" ] - external_deps = [ "napi:cj_bind_ffi" ] - } - - if (current_os == "ohos") { - defines += [ "OHOS_PLATFORM" ] - } - - if (current_os == "mingw") { - defines += [ "WINDOWS_PLATFORM" ] + defines = [ "FILE_API_TRACE" ] + branch_protector_ret = "pac_ret" + sanitize = { + integer_overflow = true + ubsan = true + boundary_sanitize = true + cfi = true + cfi_cross_dso = true + debug = false + } } innerapi_tags = [ "platformsdk" ] @@ -164,16 +137,6 @@ ohos_shared_library("cj_file_fs_ffi") { } ohos_shared_library("cj_statvfs_ffi") { - sanitize = { - integer_overflow = true - ubsan = true - boundary_sanitize = true - cfi = true - cfi_cross_dso = true - debug = false - } - - defines = [] cflags = [ "-fvisibility=hidden", "-fdata-sections", @@ -184,102 +147,34 @@ ohos_shared_library("cj_statvfs_ffi") { "-fvisibility-inlines-hidden", "-Oz", ] - if (is_mingw || is_mac || is_linux) { - defines += [ "PREVIEW" ] + branch_protector_ret = "pac_ret" + sanitize = { + integer_overflow = true + ubsan = true + boundary_sanitize = true + cfi = true + cfi_cross_dso = true + debug = false } - if (current_os == "ohos" && current_cpu == "x86_64") { - defines += [ "SIMULATOR" ] - } - if (is_ohos) { - defines += [ "OHOS_PLATFORM" ] - if (use_musl && !is_asan) { - defines += [ "HOOK_ENABLE" ] - } - } else if (is_mingw) { - defines += [ "WINDOWS_PLATFORM" ] - cflags_cc += [ "-std=c++17" ] - } else if (is_mac) { - defines += [ "MAC_PLATFORM" ] - } else if (is_linux) { - defines += [ "LINUX_PLATFORM" ] - cflags_cc += [ "-std=c++17" ] - } else if (is_arkui_x && target_os == "ios") { - defines += [ "IOS_PLATFORM" ] - } + include_dirs = [ "${file_api_path}/interfaces/kits/cj/src" ] - include_dirs = [ - "${src_path}/common", - "${src_path}/common/napi", - "${src_path}/common/napi/n_async", - "${src_path}/common/file_helper", - "${src_path}/mod_fs", - "${src_path}/mod_fs/class_randomaccessfile", - "${src_path}/mod_fs/class_readeriterator", - "${src_path}/mod_fs/properties", - "${utils_path}/common/include", - "${utils_path}/filemgmt_libhilog", - "${utils_path}/filemgmt_libh", - "${utils_path}/filemgmt_libn/include", - "${file_api_path}/interfaces/kits/cj/src", - "${file_api_path}/interfaces/kits/native/remote_uri", - "${file_api_path}/interfaces/kits/native/task_signal", - "${file_api_path}/interfaces/kits/rust/include", + sources = [ + "src/statvfs_ffi.cpp", + "src/statvfs_impl.cpp", + "src/uni_error.cpp", ] - if (!defined(defines)) { - defines = [] - } - - use_exceptions = true - - if (product_name != "ohos-sdk") { - deps = [ - "${file_api_path}/interfaces/kits/js:build_kits_js", - "${file_api_path}/interfaces/kits/js:fs", - "${file_api_path}/interfaces/kits/native:remote_uri_native", - "${file_api_path}/interfaces/kits/native:task_signal_native", - "${file_api_path}/interfaces/kits/rust:rust_file", - "${utils_path}/filemgmt_libhilog:filemgmt_libhilog", - "${utils_path}/filemgmt_libn:filemgmt_libn", - ] - external_deps = [ - "ability_base:zuri", - "ability_runtime:ability_manager", - "ability_runtime:abilitykit_native", - "access_token:libtokenid_sdk", - "app_file_service:fileuri_native", - "bounds_checking_function:libsec_shared", - "bundle_framework:appexecfwk_base", - "bundle_framework:appexecfwk_core", - "c_utils:utils", - "data_share:datashare_common", - "data_share:datashare_consumer", - "dfs_service:distributed_file_daemon_kit_inner", - "hilog:libhilog", - "ipc:ipc_core", - "napi:ace_napi", - "napi:cj_bind_ffi", - "napi:cj_bind_native", - "samgr:samgr_proxy", - ] - sources = [ - "src/statvfs_ffi.cpp", - "src/statvfs_impl.cpp", - "src/uni_error.cpp", - ] - } else { - defines += [ "PREVIEWER" ] - external_deps = [ "napi:cj_bind_ffi" ] - } - - if (current_os == "ohos") { - defines += [ "OHOS_PLATFORM" ] - } - - if (current_os == "mingw") { - defines += [ "WINDOWS_PLATFORM" ] - } + deps = [ + "${utils_path}/filemgmt_libhilog:filemgmt_libhilog", + "${utils_path}/filemgmt_libn:filemgmt_libn", + ] + external_deps = [ + "hilog:libhilog", + "napi:ace_napi", + "napi:cj_bind_ffi", + "napi:cj_bind_native", + ] innerapi_tags = [ "platformsdk" ] part_name = "file_api" diff --git a/interfaces/kits/cj/src/file_fs_ffi.cpp b/interfaces/kits/cj/src/file_fs_ffi.cpp index 0c0fa60a2904841aad37ab10e5a3c4f9336ec922..d0ee85ee47488bfb88b0bb0bc668472ed4025b21 100644 --- a/interfaces/kits/cj/src/file_fs_ffi.cpp +++ b/interfaces/kits/cj/src/file_fs_ffi.cpp @@ -650,6 +650,22 @@ RetDataBool FfiOHOSFileFsAccess(const char* path) return ret; } +RetDataBool FfiOHOSFileFsAccessExt(const char* path, int32_t mode, int32_t flag) +{ + LOGI("FS_TEST::FfiOHOSFileFsAccessExt"); + RetDataBool ret = { .code = ERR_INVALID_INSTANCE_CODE, .data = 0 }; + auto [status, accessStatus] = FileFsImpl::Access(path, mode, flag); + ret.code = status; + if (status != SUCCESS_CODE) { + LOGI("FS_TEST::FfiOHOSFileFsAccessExt error"); + ret.data = false; + return ret; + } + LOGI("FS_TEST::FfiOHOSFileFsAccessExt success"); + ret.data = accessStatus; + return ret; +} + int32_t FfiOHOSFileFsTruncateByString(const char* file, int64_t len) { LOGI("FS_TEST::FfiOHOSFileFsTruncateByString"); diff --git a/interfaces/kits/cj/src/file_fs_ffi.h b/interfaces/kits/cj/src/file_fs_ffi.h index 6c8bf94ebd91100fd54101d5719553e2062c5505..8e8015d0f7e1d5160be7cf46cf1e185e3479dec7 100644 --- a/interfaces/kits/cj/src/file_fs_ffi.h +++ b/interfaces/kits/cj/src/file_fs_ffi.h @@ -50,6 +50,7 @@ extern "C" { FFI_EXPORT int32_t FfiOHOSFileFsRename(const char* oldFile, const char* newFile); FFI_EXPORT int32_t FfiOHOSFileFsUnlink(const char* path); FFI_EXPORT RetDataBool FfiOHOSFileFsAccess(const char* path); + FFI_EXPORT RetDataBool FfiOHOSFileFsAccessExt(const char* path, int32_t mode, int32_t flag); FFI_EXPORT RetDataI64 FfiOHOSFileFsOpen(const char* path, uint64_t mode); FFI_EXPORT RetDataI64 FfiOHOSFileFsRead(int32_t fd, char* buffer, int64_t bufLen, size_t length, int64_t offset); FFI_EXPORT RetDataI64 FfiOHOSFileFsReadCur(int32_t fd, char* buffer, int64_t bufLen, size_t length); diff --git a/interfaces/kits/cj/src/file_fs_impl.cpp b/interfaces/kits/cj/src/file_fs_impl.cpp index 9b261e51ad30031c8bd9d2f44ac3dd4c9d40fc81..23b889c87bd459f020260194fe6871c8f4174e96 100644 --- a/interfaces/kits/cj/src/file_fs_impl.cpp +++ b/interfaces/kits/cj/src/file_fs_impl.cpp @@ -15,6 +15,15 @@ #include "file_fs_impl.h" +#if !defined(WIN_PLATFORM) && !defined(IOS_PLATFORM) +#include + +#include "bundle_mgr_proxy.h" +#include "ipc_skeleton.h" +#include "iservice_registry.h" +#include "system_ability_definition.h" +#endif + using namespace OHOS; using namespace OHOS::FFI; using namespace OHOS::FileManagement; @@ -23,6 +32,18 @@ using namespace OHOS::CJSystemapi::FileFs; namespace { +#if !defined(WIN_PLATFORM) && !defined(IOS_PLATFORM) +const std::string CLOUDDISK_FILE_PREFIX = "/data/storage/el2/cloud"; +const std::string DISTRIBUTED_FILE_PREFIX = "/data/storage/el2/distributedfiles"; +const std::string PACKAGE_NAME_FLAG = ""; +const std::string USER_ID_FLAG = ""; +const std::string PHYSICAL_PATH_PREFIX = "/mnt/hmdfs//account/device_view/local/data/"; +const std::string CLOUD_FILE_LOCATION = "user.cloud.location"; +const char POSITION_LOCAL = '1'; +const char POSITION_BOTH = '3'; +const int BASE_USER_RANGE = 200000; +#endif + std::tuple ParseFile(int32_t file) { if (file < 0) { @@ -106,25 +127,100 @@ std::tuple ParseRandomFile(std::string file) return { true, FileInfo { true, move(filePath), move(fdg) }, ERRNO_NOERR }; } -std::tuple GetFsAccess(const FileInfo &fileInfo) +std::tuple UvAccess(const std::string &path, int mode) { std::unique_ptr stat_req = { new (std::nothrow) uv_fs_t, CommonFunc::FsReqCleanup }; if (!stat_req) { LOGE("Failed to request heap memory."); - return {ENOMEM, false}; + return {GetErrorCode(ENOMEM), false}; } bool isAccess = false; - int ret = uv_fs_access(nullptr, stat_req.get(), fileInfo.path.get(), 0, nullptr); + int ret = uv_fs_access(nullptr, stat_req.get(), path.c_str(), mode, nullptr); if (ret < 0 && (std::string_view(uv_err_name(ret)) != "ENOENT")) { LOGE("Failed to access file by path"); - return {ret, false}; + return {GetErrorCode(ret), false}; } if (ret == 0) { isAccess = true; } return {SUCCESS_CODE, isAccess}; } + +#if !defined(WIN_PLATFORM) && !defined(IOS_PLATFORM) +bool IsCloudOrDistributedFilePath(const std::string &path) +{ + return path.find(CLOUDDISK_FILE_PREFIX) == 0 || path.find(DISTRIBUTED_FILE_PREFIX) == 0; +} + +int GetCurrentUserId() +{ + int uid = IPCSkeleton::GetCallingUid(); + int userId = uid / BASE_USER_RANGE; + return userId; +} + +sptr GetBundleMgrProxy() +{ + sptr systemAbilityManager = + OHOS::SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); + if (!systemAbilityManager) { + LOGE("Fail to get system ability mgr"); + return nullptr; + } + sptr remoteObject = + systemAbilityManager->GetSystemAbility(OHOS::BUNDLE_MGR_SERVICE_SYS_ABILITY_ID); + if (!remoteObject) { + LOGE("Fail to get bundle manager proxy"); + return nullptr; + } + return iface_cast(remoteObject); +} + +std::string GetSelfBundleName() +{ + sptr bundleMgrProxy = GetBundleMgrProxy(); + if (!bundleMgrProxy) { + LOGE("BundleMgrProxy is nullptr"); + return ""; + } + OHOS::AppExecFwk::BundleInfo bundleInfo; + auto ret = bundleMgrProxy->GetBundleInfoForSelf(0, bundleInfo); + if (ret != 0) { + LOGE("BundleName get fail"); + return ""; + } + return bundleInfo.name; +} + +std::tuple HandleLocalCheck(const std::string &path, int mode) +{ + // check if the file of /data/storage/el2/cloud is on the local + if (path.find(CLOUDDISK_FILE_PREFIX) == 0) { + char val[2] = {'\0'}; + if (getxattr(path.c_str(), CLOUD_FILE_LOCATION.c_str(), val, sizeof(val)) < 0) { + LOGE("Get cloud file location fail, err: %{public}d", errno); + return {GetErrorCode(errno), false}; + } + if (val[0] == POSITION_LOCAL || val[0] == POSITION_BOTH) { + return {SUCCESS_CODE, true}; + } + return {GetErrorCode(ENOENT), false}; + } + // check if the distributed file of /data/storage/el2/distributedfiles is on the local, + // convert into physical path(/mnt/hmdfs//account/device_view/local/data/) and check + if (path.find(DISTRIBUTED_FILE_PREFIX) == 0) { + int userId = GetCurrentUserId(); + std::string bundleName = GetSelfBundleName(); + std::string relativePath = path.substr(DISTRIBUTED_FILE_PREFIX.length()); + std::string physicalPath = PHYSICAL_PATH_PREFIX + relativePath; + physicalPath.replace(physicalPath.find(USER_ID_FLAG), USER_ID_FLAG.length(), std::to_string(userId)); + physicalPath.replace(physicalPath.find(PACKAGE_NAME_FLAG), PACKAGE_NAME_FLAG.length(), bundleName); + return UvAccess(physicalPath, mode); + } + return {GetErrorCode(ENOENT), false}; +} +#endif } namespace OHOS { @@ -147,6 +243,10 @@ std::tuple> FileFsImpl::Stat(int32_t file) if (!nativeStat) { return {GetErrorCode(ENOMEM), nullptr}; } +#if !defined(WIN_PLATFORM) && !defined(IOS_PLATFORM) + auto fileInfoPtr = std::make_shared(std::move(fileInfo)); + nativeStat->SetFileInfo(fileInfoPtr); +#endif return {SUCCESS_CODE, nativeStat}; } @@ -169,6 +269,10 @@ std::tuple> FileFsImpl::Stat(std::string file) if (!nativeStat) { return {GetErrorCode(ENOMEM), nullptr}; } +#if !defined(WIN_PLATFORM) && !defined(IOS_PLATFORM) + auto fileInfoPtr = std::make_shared(std::move(fileInfo)); + nativeStat->SetFileInfo(fileInfoPtr); +#endif return {SUCCESS_CODE, nativeStat}; } @@ -915,18 +1019,14 @@ RetDataI64 FileFsImpl::WriteCur(int32_t fd, void* buf, size_t length, std::strin return ret; } -std::tuple FileFsImpl::Access(std::string path) +std::tuple FileFsImpl::Access(std::string path, int32_t mode, int32_t flag) { - auto [fileState, fileInfo] = ParseFile(path); - - if (fileState != SUCCESS_CODE) { - return {GetErrorCode(ENOMEM), false}; - } - auto [accessState, access] = GetFsAccess(fileInfo); - if (accessState < 0) { - return {GetErrorCode(accessState), false}; +#if !defined(WIN_PLATFORM) && !defined(IOS_PLATFORM) + if (flag == LOCAL_FLAG && IsCloudOrDistributedFilePath(path)) { + return HandleLocalCheck(path, mode); } - return {SUCCESS_CODE, access}; +#endif + return UvAccess(path, mode); } int FileFsImpl::Truncate(std::string file, int64_t len) diff --git a/interfaces/kits/cj/src/file_fs_impl.h b/interfaces/kits/cj/src/file_fs_impl.h index e9ce164b29cf7570f45ff82858f8b9b873247cd2..52ac4a4d701abc38658ce58a3801042501df9ed5 100644 --- a/interfaces/kits/cj/src/file_fs_impl.h +++ b/interfaces/kits/cj/src/file_fs_impl.h @@ -61,6 +61,10 @@ struct FileStruct { FileFs::FileEntity *fileEntity; }; namespace FileFs { +enum AccessFlag : int32_t { + DEFAULT_FLAG = -1, + LOCAL_FLAG, +}; class FileFsImpl { public: static std::tuple> Stat(int32_t file); @@ -81,7 +85,7 @@ public: static RetDataI64 ReadCur(int32_t fd, char* buf, int64_t bufLen, size_t length); static RetDataI64 Write(int32_t fd, void* buf, size_t length, int64_t offset, std::string encode); static RetDataI64 WriteCur(int32_t fd, void* buf, size_t length, std::string encode); - static std::tuple Access(std::string path); + static std::tuple Access(std::string path, int32_t mode = 0, int32_t flag = DEFAULT_FLAG); static int Truncate(std::string file, int64_t len); static int Truncate(int32_t file, int64_t len); static int Close(int32_t file); diff --git a/interfaces/kits/cj/src/stat_ffi.cpp b/interfaces/kits/cj/src/stat_ffi.cpp index 93d82cdcc140ae735d78acacd5441abb0c24eda7..2d66541871e6e9e593590e77f1be7791528d2720 100644 --- a/interfaces/kits/cj/src/stat_ffi.cpp +++ b/interfaces/kits/cj/src/stat_ffi.cpp @@ -179,4 +179,17 @@ bool FfiOHOSStatIsSymbolicLink(int64_t id) } return instance->IsSymbolicLink(); } + +#if !defined(WIN_PLATFORM) && !defined(IOS_PLATFORM) +RetDataI32 FfiOHOSStatGetLocation(int64_t id) +{ + LOGI("FS_TEST:: FfiOHOSStatGetLocation"); + auto instance = FFIData::GetData(id); + if (!instance) { + LOGE("StatImpl instance not exist %{public}" PRId64, id); + return {.code = ERR_INVALID_INSTANCE_CODE, .data = 0}; + } + return instance->GetLocation(); +} +#endif } \ No newline at end of file diff --git a/interfaces/kits/cj/src/stat_ffi.h b/interfaces/kits/cj/src/stat_ffi.h index 7b99b6341d0b6b9dc192d0cd72c8b3fa8d8d270b..0c40540ee871147520089be142e8201659dc4e08 100644 --- a/interfaces/kits/cj/src/stat_ffi.h +++ b/interfaces/kits/cj/src/stat_ffi.h @@ -37,6 +37,9 @@ extern "C" { FFI_EXPORT bool FfiOHOSStatIsFile(int64_t id); FFI_EXPORT bool FfiOHOSStatIsSocket(int64_t id); FFI_EXPORT bool FfiOHOSStatIsSymbolicLink(int64_t id); +#if !defined(WIN_PLATFORM) && !defined(IOS_PLATFORM) + FFI_EXPORT RetDataI32 FfiOHOSStatGetLocation(int64_t id); +#endif } #endif // OHOS_FILE_FS_STAT_FFI_H \ No newline at end of file diff --git a/interfaces/kits/cj/src/stat_impl.cpp b/interfaces/kits/cj/src/stat_impl.cpp new file mode 100644 index 0000000000000000000000000000000000000000..7ed76e8e4d59c132c78e9b70efb3d6332bfb96d4 --- /dev/null +++ b/interfaces/kits/cj/src/stat_impl.cpp @@ -0,0 +1,61 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "stat_impl.h" +#if !defined(WIN_PLATFORM) && !defined(IOS_PLATFORM) +#include +#endif +#include "macro.h" +#include "uni_error.h" + +namespace OHOS { +namespace CJSystemapi { +namespace FileFs { +using namespace std; + +#if !defined(WIN_PLATFORM) && !defined(IOS_PLATFORM) +RetDataI32 StatImpl::GetLocation() +{ + auto value = static_cast(malloc(MAX_ATTR_NAME)); + if (value == nullptr) { + return { .code = GetErrorCode(ENOMEM), .data = LOCAL }; + } + ssize_t size = 0; + if (fileInfo_->isPath) { + size = getxattr(fileInfo_->path.get(), CLOUD_LOCATION_ATTR.c_str(), value, MAX_ATTR_NAME); + } else { + size = fgetxattr(fileInfo_->fdg->GetFD(), CLOUD_LOCATION_ATTR.c_str(), value, MAX_ATTR_NAME); + } + Location defaultLocation = LOCAL; + if (size <= 0) { + if (errno != ENODATA && errno != EOPNOTSUPP) { + LOGE("Getxattr value failed, errno is %{public}d", errno); + } + free(value); + return { .code = SUCCESS_CODE, .data = defaultLocation }; + } + std::string location = string(value, static_cast(size)); + free(value); + if (!std::all_of(location.begin(), location.end(), ::isdigit)) { + LOGE("Getxattr location is not all digit!"); + return { .code = SUCCESS_CODE, .data = defaultLocation }; + } + defaultLocation = static_cast(atoi(location.c_str())); + return { .code = SUCCESS_CODE, .data = defaultLocation }; +} +#endif +} +} +} diff --git a/interfaces/kits/cj/src/stat_impl.h b/interfaces/kits/cj/src/stat_impl.h index 36e99508f370d3944183f74ab0803b2ada7024c2..3b61dccc535e0ff6b04bcade450d8df02accbf64 100644 --- a/interfaces/kits/cj/src/stat_impl.h +++ b/interfaces/kits/cj/src/stat_impl.h @@ -33,11 +33,28 @@ namespace FileFs { constexpr int S_PREMISSION = 00000777; +#if !defined(WIN_PLATFORM) && !defined(IOS_PLATFORM) +const size_t MAX_ATTR_NAME = 64; +const std::string CLOUD_LOCATION_ATTR = "user.cloud.location"; +enum Location { + LOCAL = 1 << 0, + CLOUD = 1 << 1 +}; +#endif + class StatImpl : public OHOS::FFI::FFIData { public: OHOS::FFI::RuntimeType* GetRuntimeType() override { return GetClassType(); } explicit StatImpl(uv_stat_t stat) : real_(std::move(stat)) {} +#if !defined(WIN_PLATFORM) && !defined(IOS_PLATFORM) + RetDataI32 GetLocation(); + + void SetFileInfo(std::shared_ptr info) + { + fileInfo_ = info; + } +#endif inline int64_t GetIno() const { @@ -122,6 +139,9 @@ public: private: uv_stat_t real_; +#if !defined(WIN_PLATFORM) && !defined(IOS_PLATFORM) + std::shared_ptr fileInfo_ = nullptr; +#endif friend class OHOS::FFI::RuntimeType; friend class OHOS::FFI::TypeBase; diff --git a/interfaces/kits/cj/src/xattr.cpp b/interfaces/kits/cj/src/xattr.cpp new file mode 100644 index 0000000000000000000000000000000000000000..36a3dea673a9a4eaa75fd61b30abe3974a6aa465 --- /dev/null +++ b/interfaces/kits/cj/src/xattr.cpp @@ -0,0 +1,95 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "xattr.h" +#include +#include +#include "macro.h" +#include "securec.h" + +using namespace std; + +namespace { +constexpr size_t MAX_XATTR_SIZE = 4096; + +char* CreateCString(string str) +{ + auto ret = static_cast(malloc(str.size() + 1)); + if (ret == nullptr) { + return nullptr; + } + if (strcpy_s(ret, str.size() + 1, str.c_str()) != 0) { + free(ret); + return nullptr; + } + return ret; +} + +bool IsIllegalXattr(const char *key, const char *value) +{ + bool isIllegalKey = strnlen(key, MAX_XATTR_SIZE + 1) > MAX_XATTR_SIZE; + if (isIllegalKey) { + LOGE("key is too loog"); + } + bool isIllegalValue = strnlen(value, MAX_XATTR_SIZE + 1) > MAX_XATTR_SIZE; + if (isIllegalValue) { + LOGE("value is too loog"); + } + return isIllegalKey || isIllegalValue; +} +} + +namespace OHOS { +namespace CJSystemapi { +namespace FileFs { + +int32_t Xattr::SetSync(const char *path, const char *key, const char *value) +{ + if (IsIllegalXattr(key, value)) { + return EINVAL; + } + if (setxattr(path, key, value, strnlen(value, MAX_XATTR_SIZE), 0) < 0) { + LOGE("setxattr fail, errno is %{public}d", errno); + return errno; + } + return SUCCESS_CODE; +} + +tuple Xattr::GetSync(const char *path, const char *key) +{ + ssize_t xAttrSize = getxattr(path, key, nullptr, 0); + if (xAttrSize == -1 || xAttrSize == 0) { + auto result = CreateCString(""); + if (result == nullptr) { + return { ENOMEM, nullptr }; + } + return { SUCCESS_CODE, result }; + } + auto xAttrValue = static_cast(malloc(static_cast(xAttrSize) + 1)); + if (xAttrValue == nullptr) { + return { ENOMEM, nullptr }; + } + xAttrSize = getxattr(path, key, xAttrValue, static_cast(xAttrSize)); + if (xAttrSize == -1) { + free(xAttrValue); + return { errno, nullptr }; + } + xAttrValue[xAttrSize] = '\0'; + return { SUCCESS_CODE, xAttrValue }; +} + +} // namespace FileFs +} // namespace CJSystemapi +} // namespace OHOS diff --git a/interfaces/kits/cj/src/xattr.h b/interfaces/kits/cj/src/xattr.h new file mode 100644 index 0000000000000000000000000000000000000000..2cddf71d7790ce5754868f4fe27d8232dafcd0ac --- /dev/null +++ b/interfaces/kits/cj/src/xattr.h @@ -0,0 +1,36 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_FILE_FS_XATTR_H +#define OHOS_FILE_FS_XATTR_H + +#include +#include + +#include "cj_common_ffi.h" + +namespace OHOS { +namespace CJSystemapi { +namespace FileFs { +class Xattr final { +public: + static int32_t SetSync(const char *path, const char *key, const char *value); + static std::tuple GetSync(const char *path, const char *key); +}; +} // namespace FileFs +} // namespace CJSystemapi +} // namespace OHOS + +#endif // OHOS_FILE_FS_XATTR_H diff --git a/interfaces/kits/cj/src/xattr_ffi.cpp b/interfaces/kits/cj/src/xattr_ffi.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d9e034d641cff478cf34c8d9b756395e3aacd4ca --- /dev/null +++ b/interfaces/kits/cj/src/xattr_ffi.cpp @@ -0,0 +1,66 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "cj_common_ffi.h" +#include "macro.h" +#include "uni_error.h" +#include "xattr.h" + +namespace OHOS { +namespace CJSystemapi { +namespace FileFs { +extern "C" { + +FFI_EXPORT void FfiOHOSFileFsReleaseCString(char *str) +{ + LOGD("FS_TEST::FfiOHOSFileFsReleaseCString"); + free(str); +} + +FFI_EXPORT int32_t FfiOHOSFileFsSetXattr(const char *path, const char *key, const char *value) +{ + LOGD("FS_TEST::FfiOHOSFileFsSetXattr"); + if (path == nullptr || key == nullptr || value == nullptr) { + return ERR_INVALID_INSTANCE_CODE; + } + auto state = Xattr::SetSync(path, key, value); + if (state != SUCCESS_CODE) { + LOGE("FS_TEST::FfiOHOSFileFsSetXattr error"); + return GetErrorCode(state); + } + return SUCCESS_CODE; +} + +FFI_EXPORT RetDataCString FfiOHOSFileFsGetXattr(const char *path, const char *key) +{ + LOGD("FS_TEST::FfiOHOSFileFsGetXattr"); + RetDataCString retData = { .code = ERR_INVALID_INSTANCE_CODE, .data = nullptr }; + if (path == nullptr || key == nullptr) { + return retData; + } + auto [state, result] = Xattr::GetSync(path, key); + if (state != SUCCESS_CODE) { + LOGE("FS_TEST::FfiOHOSFileFsGetXattr error"); + retData.code = GetErrorCode(state); + return retData; + } + retData.data = result; + retData.code = SUCCESS_CODE; + return retData; +} +} +} // namespace FileFs +} // namespace CJSystemapi +} // namespace OHOS diff --git a/interfaces/kits/hyperaio/BUILD.gn b/interfaces/kits/hyperaio/BUILD.gn index 191ab9c0ed48604ce237cc9d478f25658694d9b1..93b6f3c965b738c34d705d97f27326570d488aa6 100644 --- a/interfaces/kits/hyperaio/BUILD.gn +++ b/interfaces/kits/hyperaio/BUILD.gn @@ -47,16 +47,12 @@ ohos_shared_library("HyperAio") { debug = false } } - sources = [ "src/hyperaio.cpp", "src/hyperaio_trace.cpp" ] - public_configs = [ ":hyperaio_config" ] - deps = [ ] - external_deps = [ "c_utils:utils", "hilog:libhilog", diff --git a/interfaces/kits/hyperaio/include/hyperaio.h b/interfaces/kits/hyperaio/include/hyperaio.h index 94d884d8958540543ae8ab0791a90bc636073a97..f7f64104cec9fa78cd531fc15862354d3572c36a 100644 --- a/interfaces/kits/hyperaio/include/hyperaio.h +++ b/interfaces/kits/hyperaio/include/hyperaio.h @@ -17,13 +17,15 @@ #define FILEMANAGEMENT_FILE_API_INTERFACES_KITS_IOURING_HYPER_AIO_H #include +#include +#include #include -#ifdef HYPERAIO_USE_LIBURING -#include "liburing.h" -#endif + + namespace OHOS { namespace HyperAio { #define IOURING_APP_PERMISSION (1U << 0) + #ifndef EOK #define EOK (0) #endif @@ -75,6 +77,10 @@ struct IoResponse { } }; +#define DECLARE_PIMPL(ClassName) \ + class Impl; \ + std::shared_ptr pImpl_ + class HyperAio { public: using ProcessIoResultCallBack = std::function)>; @@ -85,15 +91,12 @@ public: int32_t StartCancelReqs(CancelReqs *req); int32_t DestroyCtx(); private: + DECLARE_PIMPL(HyperAio); ProcessIoResultCallBack ioResultCallBack_ = nullptr; -#ifdef HYPERAIO_USE_LIBURING - io_uring uring_; std::thread harvestThread_; - std::atomic stopThread_; - std::atomic initialized_; + std::atomic stopThread_ = true; + std::atomic initialized_ = false; void HarvestRes(); - struct io_uring_sqe* GetSqeWithRetry(struct io_uring *ring); -#endif }; } } diff --git a/interfaces/kits/hyperaio/src/hyperaio.cpp b/interfaces/kits/hyperaio/src/hyperaio.cpp index cc81205b6dd92519d4ccd7fcadf569f221959650..1f5dc006db5daa9b77efbde83ea1972fc9105c87 100644 --- a/interfaces/kits/hyperaio/src/hyperaio.cpp +++ b/interfaces/kits/hyperaio/src/hyperaio.cpp @@ -21,7 +21,9 @@ #include "hyperaio_trace.h" #include "libhilog.h" #include "ipc_skeleton.h" - +#ifdef HYPERAIO_USE_LIBURING +#include "liburing.h" +#endif namespace OHOS { namespace HyperAio { #ifdef HYPERAIO_USE_LIBURING @@ -29,6 +31,14 @@ const uint32_t URING_QUEUE_SIZE = 512; const uint32_t DELAY = 20; const uint32_t BATCH_SIZE = 128; const uint32_t RETRIES = 3; +std::atomic openReqCount_{0}; +std::atomic readReqCount_{0}; +std::atomic cancelReqCount_{0}; +std::atomic cqeCount_{0}; +class HyperAio::Impl { +public: + io_uring uring_; +}; static bool HasAccessIouringPermission() { @@ -39,9 +49,15 @@ static bool HasAccessIouringPermission() HILOGE("have no ALLOW_IOURING permission"); return false; } + return true; } +static bool ValidateReqNum(uint32_t reqNum) +{ + return reqNum > 0 && reqNum <= URING_QUEUE_SIZE - 1; +} + uint32_t HyperAio::SupportIouring() { HyperaioTrace trace("SupportIouring"); @@ -49,21 +65,47 @@ uint32_t HyperAio::SupportIouring() if (HasAccessIouringPermission()) { flags |= IOURING_APP_PERMISSION; } + return flags; } +struct io_uring_sqe* GetSqeWithRetry(struct io_uring *ring) +{ + struct io_uring_sqe *sqe; + for (uint32_t i = 0; i < RETRIES; i++) { + sqe = io_uring_get_sqe(ring); + if (sqe != nullptr) { + return sqe; + } + io_uring_submit(ring); + std::this_thread::sleep_for(std::chrono::milliseconds(DELAY)); + } + return nullptr; +} + int32_t HyperAio::CtxInit(ProcessIoResultCallBack *callBack) { HyperaioTrace trace("CtxInit"); + if (initialized_.load()) { + HILOGE("HyperAio has been initialized"); + return EOK; + } + if (callBack == nullptr) { HILOGE("callBack is null"); return -EINVAL; } - int32_t ret = io_uring_queue_init(URING_QUEUE_SIZE, &uring_, 0); + + if (pImpl_ == nullptr) { + pImpl_ = std::make_shared(); + } + + int32_t ret = io_uring_queue_init(URING_QUEUE_SIZE, &pImpl_->uring_, 0); if (ret < 0) { HILOGE("init io_uring failed, ret = %{public}d", ret); return ret; } + ioResultCallBack_ = *callBack; stopThread_.store(false); harvestThread_ = std::thread(&HyperAio::HarvestRes, this); @@ -72,23 +114,11 @@ int32_t HyperAio::CtxInit(ProcessIoResultCallBack *callBack) return EOK; } -struct io_uring_sqe* HyperAio::GetSqeWithRetry(struct io_uring *ring) -{ - struct io_uring_sqe *sqe; - for (uint32_t i = 0; i < RETRIES; i++) { - sqe = io_uring_get_sqe(ring); - if (sqe != nullptr) { - return sqe; - } - io_uring_submit(ring); - std::this_thread::sleep_for(std::chrono::milliseconds(DELAY)); - } - return nullptr; -} - int32_t HyperAio::StartOpenReqs(OpenReqs *req) { - HyperaioTrace trace("StartOpenReqs" + std::to_string(req->reqNum)); + if (pImpl_ == nullptr) { + return -EINVAL; + } if (req == nullptr || req->reqs == nullptr) { return -EINVAL; } @@ -96,10 +126,15 @@ int32_t HyperAio::StartOpenReqs(OpenReqs *req) HILOGE("HyperAio is not initialized"); return -EPERM; } + if (!ValidateReqNum(req->reqNum)) { + HILOGE("reqNum is out of range: %{public}u", req->reqNum); + return -EINVAL; + } + HyperaioTrace trace("StartOpenReqs" + std::to_string(req->reqNum)); uint32_t totalReqs = req->reqNum; uint32_t count = 0; for (uint32_t i = 0; i < totalReqs; i++) { - struct io_uring_sqe *sqe = GetSqeWithRetry(&uring_); + struct io_uring_sqe *sqe = GetSqeWithRetry(&pImpl_->uring_); if (sqe == nullptr) { HILOGE("get sqe failed"); return -ENOMEM; @@ -108,21 +143,19 @@ int32_t HyperAio::StartOpenReqs(OpenReqs *req) io_uring_sqe_set_data(sqe, reinterpret_cast(openInfo->userData)); io_uring_prep_openat(sqe, openInfo->dfd, static_cast(openInfo->path), openInfo->flags, openInfo->mode); + HILOGD("open flags = %{public}d, mode = %{public}u, userData = %{public}lu", + openInfo->flags, openInfo->mode, openInfo->userData); + HyperaioTrace trace("open flags:" + std::to_string(openInfo->flags) + "mode:" + std::to_string(openInfo->mode) + + "userData:" + std::to_string(openInfo->userData)); count++; - if (count >= BATCH_SIZE) { - count = 0; - int32_t ret = io_uring_submit(&uring_); + if (count >= BATCH_SIZE || i == totalReqs - 1) { + int32_t ret = io_uring_submit(&pImpl_->uring_); if (ret < 0) { HILOGE("submit open reqs failed, ret = %{public}d", ret); return ret; } - } - } - if (count > 0 && count < BATCH_SIZE) { - int32_t ret = io_uring_submit(&uring_); - if (ret < 0) { - HILOGE("submit open reqs failed, ret = %{public}d", ret); - return ret; + openReqCount_ += count; + count = 0; } } return EOK; @@ -130,7 +163,9 @@ int32_t HyperAio::StartOpenReqs(OpenReqs *req) int32_t HyperAio::StartReadReqs(ReadReqs *req) { - HyperaioTrace trace("StartReadReqs" + std::to_string(req->reqNum)); + if (pImpl_ == nullptr) { + return -EINVAL; + } if (req == nullptr || req->reqs == nullptr) { return -EINVAL; } @@ -138,10 +173,15 @@ int32_t HyperAio::StartReadReqs(ReadReqs *req) HILOGE("HyperAio is not initialized"); return -EPERM; } + if (!ValidateReqNum(req->reqNum)) { + HILOGE("reqNum is out of range: %{public}u", req->reqNum); + return -EINVAL; + } + HyperaioTrace trace("StartReadReqs" + std::to_string(req->reqNum)); uint32_t totalReqs = req->reqNum; uint32_t count = 0; for (uint32_t i = 0; i < totalReqs; i++) { - struct io_uring_sqe *sqe = GetSqeWithRetry(&uring_); + struct io_uring_sqe *sqe = GetSqeWithRetry(&pImpl_->uring_); if (sqe == nullptr) { HILOGE("get sqe failed"); return -ENOMEM; @@ -149,21 +189,19 @@ int32_t HyperAio::StartReadReqs(ReadReqs *req) struct ReadInfo *readInfo = &req->reqs[i]; io_uring_sqe_set_data(sqe, reinterpret_cast(readInfo->userData)); io_uring_prep_read(sqe, readInfo->fd, readInfo->buf, readInfo->len, readInfo->offset); + HILOGD("read len = %{public}u, offset = %{public}lu, userData = %{public}lu", + readInfo->len, readInfo->offset, readInfo->userData); + HyperaioTrace trace("read len:" + std::to_string(readInfo->len) + "offset:" + std::to_string(readInfo->offset) + + "userData:" + std::to_string(readInfo->userData)); count++; - if (count >= BATCH_SIZE) { - count = 0; - int32_t ret = io_uring_submit(&uring_); + if (count >= BATCH_SIZE || i == totalReqs - 1) { + int32_t ret = io_uring_submit(&pImpl_->uring_); if (ret < 0) { HILOGE("submit read reqs failed, ret = %{public}d", ret); return ret; } - } - } - if (count > 0 && count < BATCH_SIZE) { - int32_t ret = io_uring_submit(&uring_); - if (ret < 0) { - HILOGE("submit read reqs failed, ret = %{public}d", ret); - return ret; + readReqCount_ += count; + count = 0; } } return EOK; @@ -171,7 +209,9 @@ int32_t HyperAio::StartReadReqs(ReadReqs *req) int32_t HyperAio::StartCancelReqs(CancelReqs *req) { - HyperaioTrace trace("StartCancelReqs" + std::to_string(req->reqNum)); + if (pImpl_ == nullptr) { + return -EINVAL; + } if (req == nullptr || req->reqs == nullptr) { return -EINVAL; } @@ -179,10 +219,15 @@ int32_t HyperAio::StartCancelReqs(CancelReqs *req) HILOGE("HyperAio is not initialized"); return -EPERM; } + if (!ValidateReqNum(req->reqNum)) { + HILOGE("reqNum is out of range: %{public}u", req->reqNum); + return -EINVAL; + } + HyperaioTrace trace("StartCancelReqs" + std::to_string(req->reqNum)); uint32_t totalReqs = req->reqNum; uint32_t count = 0; for (uint32_t i = 0; i < totalReqs; i++) { - struct io_uring_sqe *sqe = GetSqeWithRetry(&uring_); + struct io_uring_sqe *sqe = GetSqeWithRetry(&pImpl_->uring_); if (sqe == nullptr) { HILOGE("get sqe failed"); return -ENOMEM; @@ -190,21 +235,19 @@ int32_t HyperAio::StartCancelReqs(CancelReqs *req) struct CancelInfo *cancelInfo = &req->reqs[i]; io_uring_sqe_set_data(sqe, reinterpret_cast(cancelInfo->userData)); io_uring_prep_cancel(sqe, reinterpret_cast(cancelInfo->targetUserData), 0); + HILOGD("cancel userData = %{public}lu, targetUserData = %{public}lu", + cancelInfo->userData, cancelInfo->targetUserData); + HyperaioTrace trace("cancel userData:" + std::to_string(cancelInfo->userData) + + "targetUserData:" + std::to_string(cancelInfo->targetUserData)); count++; - if (count >= BATCH_SIZE) { - count = 0; - int32_t ret = io_uring_submit(&uring_); + if (count >= BATCH_SIZE || i == totalReqs - 1) { + int32_t ret = io_uring_submit(&pImpl_->uring_); if (ret < 0) { HILOGE("submit cancel reqs failed, ret = %{public}d", ret); return ret; } - } - } - if (count > 0 && count < BATCH_SIZE) { - int32_t ret = io_uring_submit(&uring_); - if (ret < 0) { - HILOGE("submit cancel reqs failed, ret = %{public}d", ret); - return ret; + cancelReqCount_ += count; + count = 0; } } return EOK; @@ -212,29 +255,56 @@ int32_t HyperAio::StartCancelReqs(CancelReqs *req) void HyperAio::HarvestRes() { + if (pImpl_ == nullptr) { + HILOGI("pImpl is null"); + return; + } + while (!stopThread_.load()) { struct io_uring_cqe *cqe; - int32_t ret = io_uring_wait_cqe(&uring_, &cqe); + int32_t ret = io_uring_wait_cqe(&pImpl_->uring_, &cqe); if (ret < 0 || cqe == nullptr) { HILOGI("wait cqe failed, ret = %{public}d", ret); continue; } + cqeCount_++; + if (cqe->res < 0) { + HILOGI("cqe failed, cqe->res = %{public}d", cqe->res); + } auto response = std::make_unique(cqe->user_data, cqe->res, cqe->flags); - io_uring_cqe_seen(&uring_, cqe); + HyperaioTrace trace("harvest: userdata " + std::to_string(cqe->user_data) + + " res " + std::to_string(cqe->res) + "flags " + std::to_string(cqe->flags)); + io_uring_cqe_seen(&pImpl_->uring_, cqe); if (ioResultCallBack_) { ioResultCallBack_(std::move(response)); } } + HILOGI("exit harvest thread"); } int32_t HyperAio::DestroyCtx() { + HILOGI("openReqCount = %{public}u, readReqCount = %{public}u, cancelReqCount = %{public}u, cqeCount = %{public}u", + openReqCount_.load(), readReqCount_.load(), cancelReqCount_.load(), cqeCount_.load()); + if (!initialized_.load()) { + HILOGI("not initialized"); + return EOK; + } + stopThread_.store(true); if (harvestThread_.joinable()) { + HILOGI("start harvest thread join"); harvestThread_.join(); + // This log is only printed after join() completes successfully + HILOGI("join success"); + } + + if (pImpl_ != nullptr) { + io_uring_queue_exit(&pImpl_->uring_); } - io_uring_queue_exit(&uring_); + initialized_.store(false); + HILOGI("destroy hyperaio success"); return EOK; } #else diff --git a/interfaces/kits/hyperaio/src/hyperaio_trace.cpp b/interfaces/kits/hyperaio/src/hyperaio_trace.cpp index b51c24b3404de8448460271adc7ad748ea05e9f3..4dfce0b0cd23b5d37f21033dc7264f845c88abb4 100644 --- a/interfaces/kits/hyperaio/src/hyperaio_trace.cpp +++ b/interfaces/kits/hyperaio/src/hyperaio_trace.cpp @@ -23,13 +23,13 @@ HyperaioTrace::HyperaioTrace(const std::string& value, bool isShowLog) : value_( if (isShowLog) { HILOGI("%{public}s", value_.c_str()); } - StartTrace(HITRACE_TAG_OHOS, "[HyperAio]" + value); + StartTrace(HITRACE_TAG_FILEMANAGEMENT, "[HyperAio]" + value); } void HyperaioTrace::End() { if (!isFinished_) { - FinishTrace(HITRACE_TAG_OHOS); + FinishTrace(HITRACE_TAG_FILEMANAGEMENT); isFinished_ = true; } } diff --git a/interfaces/kits/js/BUILD.gn b/interfaces/kits/js/BUILD.gn index 9fc445f9ab59139dfe499b9fb3c1c33d8d637021..f9fd98aa6b690e06584f6c0c461b485cf610796f 100644 --- a/interfaces/kits/js/BUILD.gn +++ b/interfaces/kits/js/BUILD.gn @@ -11,6 +11,7 @@ # See the License for the specific language governing permissions and # limitations under the License. +import("//build/config/components/ets_frontend/ets2abc_config.gni") import("//build/ohos.gni") import("//foundation/filemanagement/file_api/file_api.gni") @@ -58,13 +59,11 @@ ohos_shared_library("fileio") { relative_install_dir = "module" include_dirs = [ - "${arkui_napi_path}/interfaces/kits", + "src/common", "src/common/file_helper", "src/common/napi", "src/common/napi/n_async", - "//third_party/node/src", - "//third_party/libuv/include", - "//third_party/openssl/include", + "src/mod_fileio", "${utils_path}/common/include", ] @@ -116,7 +115,6 @@ ohos_shared_library("fileio") { deps = [ "${file_api_path}/interfaces/kits/native:remote_uri_native", "${utils_path}/filemgmt_libhilog:filemgmt_libhilog", - "//third_party/openssl:libcrypto_shared", ] use_exceptions = true @@ -124,8 +122,12 @@ ohos_shared_library("fileio") { external_deps = [ "ability_base:zuri", "bounds_checking_function:libsec_shared", + "c_utils:utils", "hilog:libhilog", + "libuv:uv", "napi:ace_napi", + "node:node_header_notice", + "openssl:libcrypto_shared", ] defines = [ "OPENSSL_SUPPRESS_DEPRECATED" ] } @@ -137,14 +139,12 @@ ohos_shared_library("fs") { relative_install_dir = "module/file" include_dirs = [ - "${filemanagement_service_path}/distributedfiledaemon/include/ipc", "${src_path}/common", "${src_path}/common/file_helper", "${src_path}/mod_fs", "${src_path}/mod_fs/properties", "${src_path}/mod_fs/properties/copy_listener", "${utils_path}/common/include", - "//third_party/libuv/include", ] sources = [ @@ -210,10 +210,7 @@ ohos_shared_library("fs") { debug = false } - include_dirs += [ - "${file_api_path}/interfaces/kits/rust/include", - "${filemanagement_service_path}/distributedfiledaemon/include/ipc", - ] + include_dirs += [ "${file_api_path}/interfaces/kits/rust/include" ] sources += [ "src/mod_fs/class_atomicfile/atomicfile_n_exporter.cpp", "src/mod_fs/class_randomaccessfile/randomaccessfile_n_exporter.cpp", @@ -261,6 +258,7 @@ ohos_shared_library("fs") { "hisysevent:libhisysevent", "hitrace:hitrace_meter", "ipc:ipc_core", + "libuv:uv", "samgr:samgr_proxy", ] deps += [ @@ -298,6 +296,7 @@ ohos_shared_library("hash") { relative_install_dir = "module/file" include_dirs = [ + "${src_path}/common", "${src_path}/common/file_helper", "${src_path}/mod_hash", "${src_path}/mod_hash/class_hashstream", @@ -315,13 +314,13 @@ ohos_shared_library("hash") { deps = [ "${utils_path}/filemgmt_libhilog:filemgmt_libhilog", "${utils_path}/filemgmt_libn:filemgmt_libn", - "//third_party/openssl:libcrypto_shared", ] external_deps = [ "bounds_checking_function:libsec_shared", "hilog:libhilog", "napi:ace_napi", + "openssl:libcrypto_shared", ] defines = [ "OPENSSL_SUPPRESS_DEPRECATED" ] } @@ -353,11 +352,11 @@ ohos_shared_library("file") { relative_install_dir = "module" include_dirs = [ - "${arkui_napi_path}/interfaces/kits", + "src/common", "src/common/napi", "src/common/napi/n_async", "src/common/file_helper", - "//third_party/node/src", + "src/mod_file", ] sources = file_common_src @@ -376,6 +375,7 @@ ohos_shared_library("file") { "eventhandler:libeventhandler", "hilog:libhilog", "napi:ace_napi", + "node:node_header_notice", ] if (file_api_read_optimize) { @@ -555,6 +555,7 @@ ohos_shared_library("securitylabel") { external_deps = [ "access_token:libtokenid_sdk", + "c_utils:utils", "hilog:libhilog", "ipc:ipc_core", "napi:ace_napi", @@ -588,9 +589,9 @@ ohos_shared_library("document") { relative_install_dir = "module" include_dirs = [ - "${arkui_napi_path}/interfaces/kits", + "src/common", + "src/common/napi", "src/common/napi/n_async", - "//third_party/node/src", ] sources = [ @@ -607,6 +608,7 @@ ohos_shared_library("document") { external_deps = [ "hilog:libhilog", "napi:ace_napi", + "node:node_header_notice", ] } @@ -623,3 +625,279 @@ group("build_kits_js") { ":statvfs", ] } + +group("ani_file_api") { + deps = [ + ":ani_file_fs", + ":ani_file_hash", + ":ani_file_securitylabel", + ] +} + +config("ani_config") { + include_dirs = [ + "${file_api_path}/interfaces/kits/rust/include", + "${utils_path}/common/include", + "${utils_path}/filemgmt_libfs/include", + "${utils_path}/filemgmt_libhilog", + "src/common", + "src/common/ani_helper", + "src/common/file_helper", + "src/mod_fs", + ] + + cflags = [ + "-fdata-sections", + "-ffunction-sections", + "-Oz", + ] + cflags_cc = [ + "-std=c++17", + "-fvisibility-inlines-hidden", + "-Oz", + ] +} + +ohos_shared_library("ani_file_fs") { + public_configs = [ ":ani_config" ] + include_dirs = [ + "src/mod_fs/ani", + "src/mod_fs/class_file", + "src/mod_fs/class_file/ani", + "src/mod_fs/class_stat", + "src/mod_fs/class_stat/ani", + "src/mod_fs/properties", + "src/mod_fs/properties/ani", + ] + sources = [ + "src/common/ani_helper/ani_signature.cpp", + "src/common/ani_helper/error_handler.cpp", + "src/common/ani_helper/type_converter.cpp", + "src/common/file_helper/fd_guard.cpp", + "src/mod_fs/ani/bind_function_class.cpp", + "src/mod_fs/class_file/ani/file_ani.cpp", + "src/mod_fs/class_file/ani/file_wrapper.cpp", + "src/mod_fs/class_file/file_instantiator.cpp", + "src/mod_fs/class_file/fs_file.cpp", + "src/mod_fs/class_stat/ani/stat_ani.cpp", + "src/mod_fs/class_stat/ani/stat_wrapper.cpp", + "src/mod_fs/class_stat/fs_stat.cpp", + "src/mod_fs/class_stat/stat_instantiator.cpp", + "src/mod_fs/fs_utils.cpp", + "src/mod_fs/properties/access_core.cpp", + "src/mod_fs/properties/ani/access_ani.cpp", + "src/mod_fs/properties/ani/close_ani.cpp", + "src/mod_fs/properties/ani/copy_file_ani.cpp", + "src/mod_fs/properties/ani/listfile_ani.cpp", + "src/mod_fs/properties/ani/mkdir_ani.cpp", + "src/mod_fs/properties/ani/move_ani.cpp", + "src/mod_fs/properties/ani/open_ani.cpp", + "src/mod_fs/properties/ani/read_ani.cpp", + "src/mod_fs/properties/ani/read_text_ani.cpp", + "src/mod_fs/properties/ani/rmdir_ani.cpp", + "src/mod_fs/properties/ani/truncate_ani.cpp", + "src/mod_fs/properties/ani/unlink_ani.cpp", + "src/mod_fs/properties/ani/write_ani.cpp", + "src/mod_fs/properties/close_core.cpp", + "src/mod_fs/properties/copy_file_core.cpp", + "src/mod_fs/properties/listfile_core.cpp", + "src/mod_fs/properties/mkdir_core.cpp", + "src/mod_fs/properties/move_core.cpp", + "src/mod_fs/properties/open_core.cpp", + "src/mod_fs/properties/read_core.cpp", + "src/mod_fs/properties/read_text_core.cpp", + "src/mod_fs/properties/rmdir_core.cpp", + "src/mod_fs/properties/stat_core.cpp", + "src/mod_fs/properties/truncate_core.cpp", + "src/mod_fs/properties/unlink_core.cpp", + "src/mod_fs/properties/write_core.cpp", + ] + deps = [ + ":ohos_file_fs_abc_etc", + "${file_api_path}/interfaces/kits/native:remote_uri_native", + "${file_api_path}/interfaces/kits/native:task_signal_native", + "${file_api_path}/interfaces/kits/rust:rust_file", + "${utils_path}/filemgmt_libfs:filemgmt_libfs", + "${utils_path}/filemgmt_libhilog:filemgmt_libhilog", + ] + use_exceptions = true + external_deps = [ + "ability_runtime:ability_manager", + "app_file_service:fileuri_native", + "bounds_checking_function:libsec_static", + "bundle_framework:appexecfwk_base", + "bundle_framework:appexecfwk_core", + "c_utils:utils", + "data_share:datashare_common", + "data_share:datashare_consumer", + "dfs_service:distributed_file_daemon_kit_inner", + "dfs_service:libdistributedfileutils", + "eventhandler:libeventhandler", + "hilog:libhilog", + "hisysevent:libhisysevent", + "ipc:ipc_core", + "libuv:uv", + "runtime_core:ani", + "runtime_core:ani_helpers", + "runtime_core:libarkruntime", + "samgr:samgr_proxy", + ] + + branch_protector_ret = "pac_ret" + sanitize = { + integer_overflow = true + ubsan = true + boundary_sanitize = true + cfi = true + cfi_cross_dso = true + debug = false + } + output_extension = "so" + subsystem_name = "filemanagement" + part_name = "file_api" +} + +generate_static_abc("ohos_file_fs_abc") { + base_url = "./src/mod_fs/ani/ets" + files = [ "./src/mod_fs/ani/ets/@ohos.file.fs.ets" ] + is_boot_abc = "True" + device_dst_file = "/system/framework/ohos_file_fs_abc.abc" +} + +ohos_prebuilt_etc("ohos_file_fs_abc_etc") { + source = "$target_out_dir/ohos_file_fs_abc.abc" + module_install_dir = "framework" + subsystem_name = "filemanagement" + part_name = "file_api" + deps = [ ":ohos_file_fs_abc" ] +} + +ohos_shared_library("ani_file_hash") { + public_configs = [ ":ani_config" ] + include_dirs = [ + "src/mod_hash", + "src/mod_hash/ani", + ] + sources = [ + "src/common/ani_helper/ani_signature.cpp", + "src/common/ani_helper/error_handler.cpp", + "src/common/ani_helper/type_converter.cpp", + "src/common/file_helper/fd_guard.cpp", + "src/common/file_helper/hash_file.cpp", + "src/mod_fs/fs_utils.cpp", + "src/mod_hash/ani/bind_function_class.cpp", + "src/mod_hash/ani/hash_ani.cpp", + "src/mod_hash/hash_core.cpp", + ] + + deps = [ + ":ohos_file_hash_abc_etc", + "${file_api_path}/interfaces/kits/rust:rust_file", + "${utils_path}/filemgmt_libfs:filemgmt_libfs", + "${utils_path}/filemgmt_libhilog:filemgmt_libhilog", + ] + external_deps = [ + "bounds_checking_function:libsec_static", + "eventhandler:libeventhandler", + "hilog:libhilog", + "ipc:ipc_core", + "libuv:uv", + "openssl:libcrypto_shared", + "runtime_core:ani", + "runtime_core:ani_helpers", + "runtime_core:libarkruntime", + ] + use_exceptions = true + + branch_protector_ret = "pac_ret" + sanitize = { + integer_overflow = true + ubsan = true + boundary_sanitize = true + cfi = true + cfi_cross_dso = true + debug = false + } + output_extension = "so" + subsystem_name = "filemanagement" + part_name = "file_api" +} + +generate_static_abc("ohos_file_hash_abc") { + base_url = "./src/mod_hash/ani/ets" + files = [ "./src/mod_hash/ani/ets/@ohos.file.hash.ets" ] + is_boot_abc = "True" + device_dst_file = "/system/framework/ohos_file_hash_abc.abc" +} + +ohos_prebuilt_etc("ohos_file_hash_abc_etc") { + source = "$target_out_dir/ohos_file_hash_abc.abc" + module_install_dir = "framework" + subsystem_name = "filemanagement" + part_name = "file_api" + deps = [ ":ohos_file_hash_abc" ] +} + +ohos_shared_library("ani_file_securitylabel") { + public_configs = [ ":ani_config" ] + include_dirs = [ + "src/mod_securitylabel/ani", + "src/mod_securitylabel", + ] + sources = [ + "src/common/ani_helper/ani_signature.cpp", + "src/common/ani_helper/error_handler.cpp", + "src/common/ani_helper/type_converter.cpp", + "src/common/file_helper/fd_guard.cpp", + "src/mod_fs/fs_utils.cpp", + "src/mod_securitylabel/ani/bind_function_class.cpp", + "src/mod_securitylabel/ani/securitylabel_ani.cpp", + "src/mod_securitylabel/securitylabel_core.cpp", + ] + + deps = [ + ":ohos_file_securityLabel_abc_etc", + "${file_api_path}/interfaces/kits/rust:rust_file", + "${utils_path}/filemgmt_libfs:filemgmt_libfs", + "${utils_path}/filemgmt_libhilog:filemgmt_libhilog", + ] + external_deps = [ + "bounds_checking_function:libsec_static", + "eventhandler:libeventhandler", + "hilog:libhilog", + "ipc:ipc_core", + "libuv:uv", + "runtime_core:ani", + "runtime_core:ani_helpers", + "runtime_core:libarkruntime", + ] + use_exceptions = true + + branch_protector_ret = "pac_ret" + sanitize = { + integer_overflow = true + ubsan = true + boundary_sanitize = true + cfi = true + cfi_cross_dso = true + debug = false + } + output_extension = "so" + subsystem_name = "filemanagement" + part_name = "file_api" +} + +generate_static_abc("ohos_file_securityLabel_abc") { + base_url = "./src/mod_securitylabel/ani/ets" + files = [ "./src/mod_securitylabel/ani/ets/@ohos.file.securityLabel.ets" ] + is_boot_abc = "True" + device_dst_file = "/system/framework/ohos_file_securityLabel_abc.abc" +} + +ohos_prebuilt_etc("ohos_file_securityLabel_abc_etc") { + source = "$target_out_dir/ohos_file_securityLabel_abc.abc" + module_install_dir = "framework" + subsystem_name = "filemanagement" + part_name = "file_api" + deps = [ ":ohos_file_securityLabel_abc" ] +} diff --git a/interfaces/kits/js/src/common/ani_helper/ani_helper.h b/interfaces/kits/js/src/common/ani_helper/ani_helper.h new file mode 100644 index 0000000000000000000000000000000000000000..f19c8f041bae91a3c6755dccf5ddd491b350a918 --- /dev/null +++ b/interfaces/kits/js/src/common/ani_helper/ani_helper.h @@ -0,0 +1,212 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef INTERFACES_KITS_JS_SRC_COMMON_ANI_HELPER_ANI_HELPER_H +#define INTERFACES_KITS_JS_SRC_COMMON_ANI_HELPER_ANI_HELPER_H + +#include +#include +#include + +#include + +#include "ani_signature.h" +#include "event_handler.h" +#include "event_runner.h" +#include "file_utils.h" +#include "filemgmt_libhilog.h" +#include "type_converter.h" + +namespace OHOS::FileManagement::ModuleFileIO::ANI { +using namespace std; +using namespace OHOS::FileManagement::ModuleFileIO::ANI::AniSignature; + +inline shared_ptr& GetMainHandler() { + thread_local shared_ptr mainHandler; + return mainHandler; +} + +class AniHelper { +public: + template + static ani_status SetFieldValue( + ani_env *env, const ani_class &cls, ani_object &obj, const char *fieldName, const T &value) + { + ani_field field; + auto status = env->Class_FindField(cls, fieldName, &field); + if (status != ANI_OK) { + return status; + } + + if constexpr (is_same_v || is_same_v || is_same_v) { + status = env->Object_SetField_Int(obj, field, value); + } else if constexpr (is_same_v || is_same_v) { + status = env->Object_SetField_Long(obj, field, value); + } else if constexpr (is_same_v || is_same_v) { + status = env->Object_SetField_Double(obj, field, value); + } else if constexpr (is_same_v || is_same_v) { + status = env->Object_SetField_Boolean(obj, field, value); + } else if constexpr (is_same_v || is_same_v) { + auto [succ, aniStr] = TypeConverter::ToAniString(env, value); + if (!succ) { + return ANI_ERROR; + } + status = env->Object_SetField_Ref(obj, field, move(aniStr)); + } else if constexpr (is_base_of_v) { + status = env->Object_SetField_Ref(obj, field, value); + } else { + return ANI_INVALID_TYPE; + } + return status; + } + + template + static ani_status SetPropertyValue( + ani_env *env, const ani_class &cls, ani_object &obj, const string &property, const T &value) + { + ani_method method; + string setter = "" + property; + auto status = env->Class_FindMethod(cls, setter.c_str(), nullptr, &method); + if (status != ANI_OK) { + return status; + } + + if constexpr (is_same_v || is_same_v) { + auto [succ, aniStr] = TypeConverter::ToAniString(env, value); + if (!succ) { + return ANI_ERROR; + } + status = env->Object_CallMethod_Void(obj, method, move(aniStr)); + } else if constexpr (is_base_of_v || is_same_v || is_same_v || + is_same_v || is_same_v || is_same_v || + is_same_v || is_same_v || is_same_v || + is_same_v) { + status = env->Object_CallMethod_Void(obj, method, value); + } else { + return ANI_INVALID_TYPE; + } + return status; + } + + static tuple> ParseInt64Option(ani_env *env, ani_object obj, const string &tag) + { + ani_boolean isUndefined = true; + ani_ref property; + ani_status status = ANI_ERROR; + status = env->Object_GetPropertyByName_Ref(obj, tag.c_str(), &property); + if (status != ANI_OK) { + return { false, nullopt }; + } + env->Reference_IsUndefined(property, &isUndefined); + if (isUndefined) { + return { true, nullopt }; + } + static const string longValueSig = Builder::BuildSignatureDescriptor({}, BasicTypes::longType); + ani_long value; + status = env->Object_CallMethodByName_Long( + static_cast(property), "longValue", longValueSig.c_str(), &value); + if (status != ANI_OK) { + return { false, nullopt }; + } + auto result = make_optional(static_cast(value)); + return { true, move(result) }; + } + + static tuple> ParseEncoding(ani_env *env, ani_object obj) + { + ani_boolean isUndefined; + ani_ref property; + if (ANI_OK != env->Object_GetPropertyByName_Ref(obj, "encoding", &property)) { + return { false, nullopt }; + } + env->Reference_IsUndefined(property, &isUndefined); + if (isUndefined) { + return { true, nullopt }; + } + auto [succ, encoding] = TypeConverter::ToUTF8String(env, (ani_string)property); + if (!succ) { + return { false, nullopt }; + } + return { true, make_optional(move(encoding)) }; + } + + static ani_env *&GetThreadEnvStorage() + { + static thread_local ani_env *env { nullptr }; + return env; + } + + static ani_env *GetThreadEnv(ani_vm *vm) + { + auto &env = GetThreadEnvStorage(); + if (env != nullptr) { + return env; + } + + ani_options aniArgs { 0, nullptr }; + auto status = vm->AttachCurrentThread(&aniArgs, ANI_VERSION_1, &env); + if (status != ANI_OK) { + status = vm->GetEnv(ANI_VERSION_1, &env); + if (status != ANI_OK) { + HILOGE("vm GetEnv, err: %{private}d", status); + return nullptr; + } + } + return env; + } + + static void DetachThreadEnv(ani_vm *vm) + { + if (vm && GetThreadEnvStorage()) { + auto status = vm->DetachCurrentThread(); + if (status != ANI_OK) { + HILOGE("Detach thread env from vm failed! status: %{private}d", status); + return; + } + GetThreadEnvStorage() = nullptr; + } + } + + static bool SendEventToMainThread(const function &func) + { + if (func == nullptr) { + HILOGE("func is nullptr!"); + return false; + } + + auto& mainHandler = GetMainHandler(); + if (mainHandler == nullptr) { + shared_ptr runner = OHOS::AppExecFwk::EventRunner::GetMainEventRunner(); + if (!runner) { + HILOGE("get main event runner failed!"); + return false; + } + mainHandler = CreateSharedPtr(runner); + if (mainHandler == nullptr) { + HILOGE("Failed to request heap memory."); + return false; + } + } + bool succ = mainHandler->PostTask(func, "", 0, OHOS::AppExecFwk::EventQueue::Priority::HIGH, {}); + if (!succ) { + HILOGE("Failed to post task to main thread."); + return false; + } + return true; + } +}; + +} // namespace OHOS::FileManagement::ModuleFileIO::ANI +#endif // INTERFACES_KITS_JS_SRC_COMMON_ANI_HELPER_ANI_HELPER_H \ No newline at end of file diff --git a/interfaces/kits/js/src/common/ani_helper/ani_signature.cpp b/interfaces/kits/js/src/common/ani_helper/ani_signature.cpp new file mode 100644 index 0000000000000000000000000000000000000000..4a683a78389923e50500cae3dfe396b8b81857c8 --- /dev/null +++ b/interfaces/kits/js/src/common/ani_helper/ani_signature.cpp @@ -0,0 +1,137 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "ani_signature.h" + +namespace OHOS::FileManagement::ModuleFileIO::ANI::AniSignature { +// BasicTypes +const Type BasicTypes::undefinedType = Builder::BuildUndefined(); +const Type BasicTypes::nullType = Builder::BuildNull(); +const Type BasicTypes::booleanType = Builder::BuildBoolean(); +const Type BasicTypes::byteType = Builder::BuildByte(); +const Type BasicTypes::charType = Builder::BuildChar(); +const Type BasicTypes::shortType = Builder::BuildShort(); +const Type BasicTypes::intType = Builder::BuildInt(); +const Type BasicTypes::longType = Builder::BuildLong(); +const Type BasicTypes::floatType = Builder::BuildFloat(); +const Type BasicTypes::doubleType = Builder::BuildDouble(); +// BoxedTypes::Boolean +const Type BoxedTypes::Boolean::classType = Builder::BuildClass("std.core.Boolean"); +const string BoxedTypes::Boolean::classDesc = BoxedTypes::Double::classType.Descriptor(); +const string BoxedTypes::Boolean::unboxedDesc = "unboxed"; +const string BoxedTypes::Boolean::unboxedSig = Builder::BuildSignatureDescriptor({}, BasicTypes::booleanType); +// BoxedTypes::Int +const Type BoxedTypes::Int::classType = Builder::BuildClass("std.core.Int"); +const string BoxedTypes::Int::classDesc = BoxedTypes::Int::classType.Descriptor(); +// BoxedTypes::Double +const Type BoxedTypes::Double::classType = Builder::BuildClass("std.core.Double"); +const string BoxedTypes::Double::classDesc = BoxedTypes::Double::classType.Descriptor(); +// BaseType +const string BaseType::ctorDesc = Builder::BuildConstructorName(); +const string BaseType::ctorSig0 = Builder::BuildSignatureDescriptor({}); +// BuiltInTypes::Object +const Type BuiltInTypes::Object::classType = Builder::BuildClass("std.core.Object"); +const string BuiltInTypes::Object::classDesc = BuiltInTypes::Object::classType.Descriptor(); +// BuiltInTypes::String +const Type BuiltInTypes::String::classType = Builder::BuildClass("std.core.String"); +const string BuiltInTypes::String::classDesc = BuiltInTypes::String::classType.Descriptor(); +// BuiltInTypes::Array +const Type BuiltInTypes::Array::classType = Builder::BuildClass("escompat.Array"); +const string BuiltInTypes::Array::classDesc = BuiltInTypes::Array::classType.Descriptor(); +const string BuiltInTypes::Array::ctorSig = Builder::BuildSignatureDescriptor({ BasicTypes::intType }); +const string BuiltInTypes::Array::getterDesc = "$_get"; +const string BuiltInTypes::Array::setterDesc = "$_set"; +const string BuiltInTypes::Array::objectGetterSig = + Builder::BuildSignatureDescriptor({ BasicTypes::intType }, BuiltInTypes::objectType); +const string BuiltInTypes::Array::objectSetterSig = + Builder::BuildSignatureDescriptor({ BasicTypes::intType, BuiltInTypes::objectType }); +// BuiltInTypes::ArrayBuffer +const Type BuiltInTypes::ArrayBuffer::classType = Builder::BuildClass("escompat.ArrayBuffer"); +const string BuiltInTypes::ArrayBuffer::classDesc = BuiltInTypes::ArrayBuffer::classType.Descriptor(); +// BuiltInTypes::BigInt +const Type BuiltInTypes::BigInt::classType = Builder::BuildClass("escompat.BigInt"); +const string BuiltInTypes::BigInt::classDesc = BuiltInTypes::BigInt::classType.Descriptor(); +const string BuiltInTypes::BigInt::ctorSig = Builder::BuildSignatureDescriptor({ BasicTypes::doubleType }); +// BuiltInTypes::BusinessError +const Type BuiltInTypes::BusinessError::classType = Builder::BuildClass("@ohos.base.BusinessError"); +const string BuiltInTypes::BusinessError::classDesc = BuiltInTypes::BusinessError::classType.Descriptor(); +// FS::ConflictFilesInner +const Type FS::ConflictFilesInner::classType = Builder::BuildClass("@ohos.file.fs.ConflictFilesInner"); +const string FS::ConflictFilesInner::classDesc = FS::ConflictFilesInner::classType.Descriptor(); +const string FS::ConflictFilesInner::ctorSig = + Builder::BuildSignatureDescriptor({ BuiltInTypes::stringType, BuiltInTypes::stringType }); +// FS::FileInner +const Type FS::FileInner::classType = Builder::BuildClass("@ohos.file.fs.fileIo.FileInner"); +const string FS::FileInner::classDesc = FS::FileInner::classType.Descriptor(); +const string FS::FileInner::ctorSig = Builder::BuildSignatureDescriptor({ BasicTypes::longType }); +// FS::ProgressInner +const Type FS::ProgressInner::classType = Builder::BuildClass("@ohos.file.fs.fileIo.ProgressInner"); +const string FS::ProgressInner::classDesc = FS::ProgressInner::classType.Descriptor(); +const string FS::ProgressInner::ctorSig = + Builder::BuildSignatureDescriptor({ BasicTypes::doubleType, BasicTypes::doubleType }); +// FS::RandomAccessFileInner +const Type FS::RandomAccessFileInner::classType = Builder::BuildClass("@ohos.file.fs.fileIo.RandomAccessFileInner"); +const string FS::RandomAccessFileInner::classDesc = FS::RandomAccessFileInner::classType.Descriptor(); +const string FS::RandomAccessFileInner::ctorSig = Builder::BuildSignatureDescriptor({ BasicTypes::longType }); +// FS::ReaderIteratorInner +const Type FS::ReaderIteratorInner::classType = Builder::BuildClass("@ohos.file.fs.fileIo.ReaderIteratorInner"); +const string FS::ReaderIteratorInner::classDesc = FS::ReaderIteratorInner::classType.Descriptor(); +const string FS::ReaderIteratorInner::ctorSig = Builder::BuildSignatureDescriptor({ BasicTypes::longType }); +// FS::ReaderIteratorResultInner +const Type FS::ReaderIteratorResultInner::classType = + Builder::BuildClass("@ohos.file.fs.fileIo.ReaderIteratorResultInner"); +const string FS::ReaderIteratorResultInner::classDesc = FS::ReaderIteratorResultInner::classType.Descriptor(); +const string FS::ReaderIteratorResultInner::ctorSig = Builder::BuildSignatureDescriptor({ BasicTypes::longType }); +// FS::StatInner +const Type FS::StatInner::classType = Builder::BuildClass("@ohos.file.fs.fileIo.StatInner"); +const string FS::StatInner::classDesc = FS::StatInner::classType.Descriptor(); +const string FS::StatInner::ctorSig = Builder::BuildSignatureDescriptor({ BasicTypes::longType }); +// FS::StreamInner +const Type FS::StreamInner::classType = Builder::BuildClass("@ohos.file.fs.fileIo.StreamInner"); +const string FS::StreamInner::classDesc = FS::StreamInner::classType.Descriptor(); +const string FS::StreamInner::ctorSig = Builder::BuildSignatureDescriptor({ BasicTypes::longType }); +// FS::TaskSignal +const Type FS::TaskSignal::classType = Builder::BuildClass("@ohos.file.fs.fileIo.TaskSignal"); +const string FS::TaskSignal::classDesc = FS::TaskSignal::classType.Descriptor(); +const string FS::TaskSignal::ctorSig = Builder::BuildSignatureDescriptor({ BasicTypes::longType }); +// FS::WatcherInner +const Type FS::WatcherInner::classType = Builder::BuildClass("@ohos.file.fs.fileIo.WatcherInner"); +const string FS::WatcherInner::classDesc = FS::WatcherInner::classType.Descriptor(); +const string FS::WatcherInner::ctorSig = Builder::BuildSignatureDescriptor({ BasicTypes::longType }); +// FS::WatchEventInner +const Type FS::WatchEventInner::classType = Builder::BuildClass("@ohos.file.fs.WatchEventInner"); +const string FS::WatchEventInner::classDesc = FS::WatchEventInner::classType.Descriptor(); +const string FS::WatchEventInner::ctorSig = + Builder::BuildSignatureDescriptor({ BuiltInTypes::stringType, BasicTypes::doubleType, BasicTypes::doubleType }); +// FS::LocationType +const Type FS::LocationType::classType = Builder::BuildClass("@ohos.file.fs.fileIo.LocationType"); +const string FS::LocationType::classDesc = FS::LocationType::classType.Descriptor(); +// Impl::EnvironmentImpl +const Type Impl::EnvironmentImpl::classType = Builder::BuildClass("@ohos.file.environment.EnvironmentImpl"); +const string Impl::EnvironmentImpl::classDesc = Impl::EnvironmentImpl::classType.Descriptor(); +// Impl::FileIoImpl +const Type Impl::FileIoImpl::classType = Builder::BuildClass("@ohos.file.fs.FileIoImpl"); +const string Impl::FileIoImpl::classDesc = Impl::FileIoImpl::classType.Descriptor(); +// Impl::HashImpl +const Type Impl::HashImpl::classType = Builder::BuildClass("@ohos.file.hash.HashImpl"); +const string Impl::HashImpl::classDesc = Impl::HashImpl::classType.Descriptor(); +// Impl::SecurityLabelImpl +const Type Impl::SecurityLabelImpl::classType = Builder::BuildClass("@ohos.file.securityLabel.SecurityLabelImpl"); +const string Impl::SecurityLabelImpl::classDesc = Impl::SecurityLabelImpl::classType.Descriptor(); +// Impl::StatvfsImpl +const Type Impl::StatvfsImpl::classType = Builder::BuildClass("@ohos.file.statvfs.StatvfsImpl"); +const string Impl::StatvfsImpl::classDesc = Impl::StatvfsImpl::classType.Descriptor(); + +} // namespace OHOS::FileManagement::ModuleFileIO::ANI::AniSignature \ No newline at end of file diff --git a/interfaces/kits/js/src/common/ani_helper/ani_signature.h b/interfaces/kits/js/src/common/ani_helper/ani_signature.h new file mode 100644 index 0000000000000000000000000000000000000000..8b7e4328169b56ae56340086e9ef251da41e2c4c --- /dev/null +++ b/interfaces/kits/js/src/common/ani_helper/ani_signature.h @@ -0,0 +1,217 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef INTERFACES_KITS_JS_SRC_COMMON_ANI_HELPER_ANI_SIGNATURE_H +#define INTERFACES_KITS_JS_SRC_COMMON_ANI_HELPER_ANI_SIGNATURE_H + +#pragma once + +#include +#include + +namespace OHOS::FileManagement::ModuleFileIO::ANI::AniSignature { +using namespace std; +using namespace arkts::ani_signature; + +struct BasicTypes { + static const Type undefinedType; + static const Type nullType; + static const Type booleanType; + static const Type byteType; + static const Type charType; + static const Type shortType; + static const Type intType; + static const Type longType; + static const Type floatType; + static const Type doubleType; +}; + +struct BaseType { + static const string ctorDesc; + static const string ctorSig0; +}; + +namespace BoxedTypes { + +struct Boolean : public BaseType { + static const Type classType; + static const string classDesc; + static const string unboxedDesc; + static const string unboxedSig; +}; + +struct Int : public BaseType { + static const Type classType; + static const string classDesc; +}; + +struct Double : public BaseType { + static const Type classType; + static const string classDesc; +}; + +} // namespace BoxedTypes + +namespace BuiltInTypes { + +struct Object : public BaseType { + static const Type classType; + static const string classDesc; +}; + +inline const Type &objectType = BuiltInTypes::Object::classType; + +struct String : public BaseType { + static const Type classType; + static const string classDesc; +}; + +inline const Type &stringType = BuiltInTypes::String::classType; + +struct Array : public BaseType { + static const Type classType; + static const string classDesc; + static const string ctorSig; + static const string getterDesc; + static const string setterDesc; + static const string objectGetterSig; + static const string objectSetterSig; +}; + +struct ArrayBuffer : public BaseType { + static const Type classType; + static const string classDesc; +}; + +struct BigInt : public BaseType { + static const Type classType; + static const string classDesc; + static const string ctorSig; +}; + +struct BusinessError : public BaseType { + static const Type classType; + static const string classDesc; +}; + +}; // namespace BuiltInTypes + +namespace FS { + +struct ConflictFilesInner : public BaseType { + static const Type classType; + static const string classDesc; + static const string ctorSig; +}; + +struct FileInner : public BaseType { + static const Type classType; + static const string classDesc; + static const string ctorSig; +}; + +struct ProgressInner : public BaseType { + static const Type classType; + static const string classDesc; + static const string ctorSig; +}; + +struct RandomAccessFileInner : public BaseType { + static const Type classType; + static const string classDesc; + static const string ctorSig; +}; + +struct ReaderIteratorInner : public BaseType { + static const Type classType; + static const string classDesc; + static const string ctorSig; +}; + +struct ReaderIteratorResultInner : public BaseType { + static const Type classType; + static const string classDesc; + static const string ctorSig; +}; + +struct StatInner : public BaseType { + static const Type classType; + static const string classDesc; + static const string ctorSig; +}; + +struct StreamInner : public BaseType { + static const Type classType; + static const string classDesc; + static const string ctorSig; +}; + +struct TaskSignal : public BaseType { + static const Type classType; + static const string classDesc; + static const string ctorSig; +}; + +struct WatcherInner : public BaseType { + static const Type classType; + static const string classDesc; + static const string ctorSig; +}; + +struct WatchEventInner : public BaseType { + static const Type classType; + static const string classDesc; + static const string ctorSig; +}; + +struct LocationType : public BaseType { + static const Type classType; + static const string classDesc; +}; + +} // namespace FS + +namespace Impl { + +struct EnvironmentImpl : public BaseType { + static const Type classType; + static const string classDesc; +}; + +struct FileIoImpl : public BaseType { + static const Type classType; + static const string classDesc; +}; + +struct HashImpl : public BaseType { + static const Type classType; + static const string classDesc; +}; + +struct SecurityLabelImpl : public BaseType { + static const Type classType; + static const string classDesc; +}; + +struct StatvfsImpl : public BaseType { + static const Type classType; + static const string classDesc; +}; + +} // namespace Impl + +} // namespace OHOS::FileManagement::ModuleFileIO::ANI::AniSignature + +#endif // INTERFACES_KITS_JS_SRC_COMMON_ANI_HELPER_ANI_SIGNATURE_H \ No newline at end of file diff --git a/interfaces/kits/js/src/common/ani_helper/bind_function.h b/interfaces/kits/js/src/common/ani_helper/bind_function.h new file mode 100644 index 0000000000000000000000000000000000000000..548865bb43f528a52ac4367e7cd536b4f4b84ee3 --- /dev/null +++ b/interfaces/kits/js/src/common/ani_helper/bind_function.h @@ -0,0 +1,86 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef INTERFACES_KITS_JS_SRC_COMMON_ANI_HELPER_BIND_FUNCTION_H +#define INTERFACES_KITS_JS_SRC_COMMON_ANI_HELPER_BIND_FUNCTION_H + +#include +#include +#include "filemgmt_libhilog.h" + +namespace OHOS { +namespace FileManagement { +namespace ModuleFileIO { +namespace ANI { + +template +ANI_EXPORT ani_status BindClass(ani_env *env, const char *className, const std::array &methods) +{ + if (env == nullptr) { + HILOGE("Invalid parameter env"); + return ANI_INVALID_ARGS; + } + + if (className == nullptr) { + HILOGE("Invalid parameter className"); + return ANI_INVALID_ARGS; + } + + ani_class cls; + if (ANI_OK != env->FindClass(className, &cls)) { + HILOGE("Cannot find class '%{private}s'", className); + return ANI_NOT_FOUND; + } + + if (ANI_OK != env->Class_BindNativeMethods(cls, methods.data(), methods.size())) { + HILOGE("Cannot bind native methods to '%{private}s'", className); + return ANI_ERROR; + }; + return ANI_OK; +} + +template +ANI_EXPORT ani_status BindNamespace( + ani_env *env, const char *namespaceStr, const std::array &methods) +{ + if (env == nullptr) { + HILOGE("Invalid parameter env"); + return ANI_INVALID_ARGS; + } + + if (namespaceStr == nullptr) { + HILOGE("Invalid parameter namespaceStr"); + return ANI_INVALID_ARGS; + } + + ani_namespace ns; + if (ANI_OK != env->FindNamespace(namespaceStr, &ns)) { + HILOGE("Cannot find namespace '%{private}s'", namespaceStr); + return ANI_NOT_FOUND; + } + + if (ANI_OK != env->Namespace_BindNativeFunctions(ns, methods.data(), methods.size())) { + HILOGE("Cannot bind native methods to '%{private}s'", namespaceStr); + return ANI_ERROR; + }; + return ANI_OK; +} + +} // namespace ANI +} // namespace ModuleFileIO +} // namespace FileManagement +} // namespace OHOS + +#endif // INTERFACES_KITS_JS_SRC_COMMON_ANI_HELPER_BIND_FUNCTION_H \ No newline at end of file diff --git a/interfaces/kits/js/src/common/ani_helper/error_handler.cpp b/interfaces/kits/js/src/common/ani_helper/error_handler.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c56a4dc0d26aaacdb2c42811d411d47d4341421d --- /dev/null +++ b/interfaces/kits/js/src/common/ani_helper/error_handler.cpp @@ -0,0 +1,27 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "error_handler.h" + +namespace OHOS::FileManagement::ModuleFileIO::ANI { + +ani_status ErrorHandler::Throw( + ani_env *env, int32_t code, const std::string &errMsg, const std::optional &errData) +{ + auto classDesc = BuiltInTypes::BusinessError::classDesc.c_str(); + return Throw(env, classDesc, code, errMsg, errData); +} + +} // namespace OHOS::FileManagement::ModuleFileIO::ANI \ No newline at end of file diff --git a/interfaces/kits/js/src/common/ani_helper/error_handler.h b/interfaces/kits/js/src/common/ani_helper/error_handler.h new file mode 100644 index 0000000000000000000000000000000000000000..12f1384dc4f9b46e87a418aa166b305748492dda --- /dev/null +++ b/interfaces/kits/js/src/common/ani_helper/error_handler.h @@ -0,0 +1,144 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef INTERFACES_KITS_JS_SRC_COMMON_ANI_HELPER_ERROR_HANDLER_H +#define INTERFACES_KITS_JS_SRC_COMMON_ANI_HELPER_ERROR_HANDLER_H + +#include +#include +#include +#include "ani_helper.h" +#include "ani_signature.h" +#include "filemgmt_libhilog.h" +#include "fs_error.h" +#include "type_converter.h" + +namespace OHOS::FileManagement::ModuleFileIO::ANI { +using namespace OHOS::FileManagement::ModuleFileIO::ANI::AniSignature; + +class ErrorHandler { +public: + static ani_status Throw( + ani_env *env, int32_t code, const std::string &errMsg, const std::optional &errData = std::nullopt); + + static ani_status Throw(ani_env *env, int32_t code, const std::optional &errData = std::nullopt) + { + if (env == nullptr) { + HILOGE("Invalid parameter env"); + return ANI_INVALID_ARGS; + } + FsError err(code); + return Throw(env, std::move(err), errData); + } + + static ani_status Throw(ani_env *env, const FsError &err, const std::optional &errData = std::nullopt) + { + if (env == nullptr) { + HILOGE("Invalid parameter env"); + return ANI_INVALID_ARGS; + } + auto code = err.GetErrNo(); + const auto &errMsg = err.GetErrMsg(); + return Throw(env, code, errMsg, errData); + } + +private: + static ani_status Throw(ani_env *env, const char *className, int32_t code, const std::string &errMsg, + const std::optional &errData = std::nullopt) + { + if (env == nullptr) { + HILOGE("Invalid parameter env"); + return ANI_INVALID_ARGS; + } + + if (className == nullptr) { + HILOGE("Invalid parameter className"); + return ANI_INVALID_ARGS; + } + + auto [status, err] = CreateErrorObj(env, className, code, errMsg, errData); + + if (status != ANI_OK) { + HILOGE("Create error object failed!"); + return status; + } + + status = env->ThrowError(err); + if (status != ANI_OK) { + HILOGE("Throw ani error object failed!"); + return status; + } + return ANI_OK; + } + + static std::tuple CreateErrorObj(ani_env *env, const char *className, int32_t code, + const std::string &errMsg, const std::optional &errData = std::nullopt) + { + ani_class cls; + if (ANI_OK != env->FindClass(className, &cls)) { + HILOGE("Cannot find class '%{private}s'", className); + return { ANI_NOT_FOUND, nullptr }; + } + + auto ctorDesc = BaseType::ctorDesc.c_str(); + auto ctorSig = BaseType::ctorSig0.c_str(); + ani_method ctor; + if (ANI_OK != env->Class_FindMethod(cls, ctorDesc, ctorSig, &ctor)) { + HILOGE("Cannot find constructor for class '%{private}s'", className); + return { ANI_NOT_FOUND, nullptr }; + } + + ani_object obj; + if (ANI_OK != env->Object_New(cls, ctor, &obj)) { + HILOGE("Cannot create ani error object"); + return { ANI_ERROR, nullptr }; + } + + auto [succ, message] = TypeConverter::ToAniString(env, errMsg); + if (!succ) { + HILOGE("Convert errMsg to ani string failed"); + return { ANI_ERROR, nullptr }; + } + + ani_status status = ANI_ERROR; + + status = env->Object_SetPropertyByName_Ref(obj, "message", message); + if (status != ANI_OK) { + HILOGE("Set property 'message' value failed"); + return { status, nullptr }; + } + + status = env->Object_SetPropertyByName_Double(obj, "code", static_cast(code)); + if (status != ANI_OK) { + HILOGE("Set property 'code' value failed"); + return { status, nullptr }; + } + + if (errData.has_value()) { + status = env->Object_SetPropertyByName_Ref(obj, "data", errData.value()); + if (status != ANI_OK) { + HILOGE("Set property 'data' value failed"); + return { status, nullptr }; + } + } + + ani_error err = static_cast(obj); + return { ANI_OK, std::move(err) }; + } +}; + +} // namespace OHOS::FileManagement::ModuleFileIO::ANI + +#endif // INTERFACES_KITS_JS_SRC_COMMON_ANI_HELPER_ERROR_HANDLER_H \ No newline at end of file diff --git a/interfaces/kits/js/src/common/ani_helper/type_converter.cpp b/interfaces/kits/js/src/common/ani_helper/type_converter.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d794b727d4cab76f7efd30bcef2c28cbdcd5f2c6 --- /dev/null +++ b/interfaces/kits/js/src/common/ani_helper/type_converter.cpp @@ -0,0 +1,297 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "type_converter.h" + +#include +#include +#include + +#include "ani_signature.h" +#include "file_utils.h" +#include "filemgmt_libhilog.h" +#include "securec.h" + +namespace OHOS::FileManagement::ModuleFileIO::ANI { +using namespace OHOS::FileManagement::ModuleFileIO::ANI::AniSignature; + +std::tuple TypeConverter::ToUTF8String(ani_env *env, const ani_string &path) +{ + if (env == nullptr) { + return { false, EMPTY_STRING }; + } + ani_size sz {}; + std::string result; + auto status = env->String_GetUTF8Size(path, &sz); + if (status != ANI_OK) { + return { false, EMPTY_STRING }; + } + result.resize(sz + 1); + status = env->String_GetUTF8SubString(path, 0, sz, result.data(), result.size(), &sz); + if (status != ANI_OK) { + return { false, EMPTY_STRING }; + } + result.resize(sz); + return { true, std::move(result) }; +} + +std::tuple> TypeConverter::ToOptionalInt32(ani_env *env, const ani_object &value) +{ + if (env == nullptr) { + return { false, {} }; + } + ani_boolean isUndefined; + env->Reference_IsUndefined(value, &isUndefined); + if (isUndefined) { + return { true, std::nullopt }; + } + + ani_int intValue; + if (ANI_OK == env->Object_CallMethodByName_Int(value, "intValue", nullptr, &intValue)) { + return { true, std::make_optional(intValue) }; + } + + return { false, {} }; +} + +std::tuple> TypeConverter::ToOptionalInt64(ani_env *env, const ani_object &value) +{ + if (env == nullptr) { + return { false, {} }; + } + + ani_boolean isUndefined; + env->Reference_IsUndefined(value, &isUndefined); + if (isUndefined) { + return { true, std::nullopt }; + } + + ani_long longValue; + if (ANI_OK == env->Object_CallMethodByName_Long(value, "longValue", nullptr, &longValue)) { + return { true, std::make_optional(longValue) }; + } + + return { false, {} }; +} + +std::tuple TypeConverter::ToAniString(ani_env *env, std::string str) +{ + if (env == nullptr) { + return { false, {} }; + } + + ani_string result; + if (ANI_OK != env->String_NewUTF8(str.c_str(), str.size(), &result)) { + return { false, {} }; + } + return { true, std::move(result) }; +} + +std::tuple TypeConverter::ToAniString(ani_env *env, std::string str, size_t size) +{ + if (env == nullptr) { + return { false, {} }; + } + + ani_string result; + if (ANI_OK != env->String_NewUTF8(str.c_str(), size, &result)) { + return { false, {} }; + } + return { true, std::move(result) }; +} + +std::tuple TypeConverter::ToAniString(ani_env *env, const char *str) +{ + if (env == nullptr || str == nullptr) { + return { false, {} }; + } + + size_t length = std::strlen(str); + ani_string result; + if (ANI_OK != env->String_NewUTF8(str, length, &result)) { + return { false, {} }; + } + return { true, std::move(result) }; +} + +std::tuple> TypeConverter::EnumToInt32(ani_env *env, const ani_enum_item &enumOp) +{ + ani_boolean isUndefined; + env->Reference_IsUndefined(enumOp, &isUndefined); + if (isUndefined) { + return { true, std::nullopt }; + } + + ani_int result; + if (ANI_OK != env->EnumItem_GetValue_Int(enumOp, &result)) { + return { false, {} }; + } + + return { true, std::make_optional(result) }; +} + +static std::tuple ParseFd(ani_env *env, const ani_object &pathOrFd) +{ + ani_boolean isFd = false; + + auto classDesc = BoxedTypes::Double::classDesc.c_str(); + ani_class cls; + env->FindClass(classDesc, &cls); + env->Object_InstanceOf(pathOrFd, cls, &isFd); + if (isFd) { + ani_int fd; + if (ANI_OK != env->Object_CallMethodByName_Int(pathOrFd, "intValue", nullptr, &fd)) { + HILOGE("Parse file path failed"); + return { false, 0 }; + } + return { true, fd }; + } + + return { false, 0 }; +} + +std::tuple TypeConverter::ToFileInfo(ani_env *env, const ani_object &pathOrFd) +{ + if (env == nullptr) { + HILOGE("Invalid parameter env"); + return { false, FileInfo { false, {}, {} } }; + } + + auto stringClassDesc = BuiltInTypes::String::classDesc.c_str(); + ani_class stringClass; + env->FindClass(stringClassDesc, &stringClass); + + ani_boolean isPath = false; + env->Object_InstanceOf(pathOrFd, stringClass, &isPath); + if (isPath) { + auto [succ, path] = TypeConverter::ToUTF8String(env, static_cast(pathOrFd)); + if (!succ) { + HILOGE("Parse file path failed"); + return { false, FileInfo { false, {}, {} } }; + } + size_t length = path.length() + 1; + auto chars = std::make_unique(length); + auto ret = strncpy_s(chars.get(), length, path.c_str(), length - 1); + if (ret != EOK) { + HILOGE("Copy file path failed!"); + return { false, FileInfo { false, {}, {} } }; + } + return { true, FileInfo { true, move(chars), {} } }; + } + + auto [isFd, fd] = ParseFd(env, pathOrFd); + if (isFd) { + auto fdg = CreateUniquePtr(fd, false); + if (fdg == nullptr) { + HILOGE("Failed to request heap memory."); + return { false, FileInfo { false, {}, {} } }; + } + return { true, FileInfo { false, {}, move(fdg) } }; + } + + return { false, FileInfo { false, {}, {} } }; +} + +std::tuple TypeConverter::ToArrayBuffer(ani_env *env, ani_arraybuffer &buffer) +{ + if (env == nullptr) { + return { false, ArrayBuffer { nullptr, 0 } }; + } + + void *buf = nullptr; + ani_size length = 0; + + if (ANI_OK != env->ArrayBuffer_GetInfo(buffer, &buf, &length)) { + return { false, ArrayBuffer { nullptr, 0 } }; + } + return { true, ArrayBuffer { std::move(buf), length } }; +} + +std::tuple TypeConverter::ToAniArrayBuffer(ani_env *env, void *buffer, size_t length) +{ + if (env == nullptr) { + return { false, nullptr }; + } + + static const char *className = "Lescompat/ArrayBuffer;"; + ani_status ret; + ani_class cls; + if ((ret = env->FindClass(className, &cls)) != ANI_OK) { + HILOGE("Not found %{private}s, err: %{public}d", className, ret); + return { false, nullptr }; + } + + ani_method ctor; + if ((ret = env->Class_FindMethod(cls, "", "I:V", &ctor)) != ANI_OK) { + HILOGE("Not found ctor, err: %{public}d", ret); + return { false, nullptr }; + } + + ani_object obj; + if ((ret = env->Object_New(cls, ctor, &obj, length)) != ANI_OK) { + HILOGE("New Uint8Array err: %{public}d", ret); + return { false, nullptr }; + } + + if (!buffer || !length) { + return { true, static_cast(obj) }; + } + + void *buf = nullptr; + ani_size len = 0; + + if ((ANI_OK != env->ArrayBuffer_GetInfo(static_cast(obj), &buf, &len)) && (!buf)) { + return { false, nullptr }; + } + + int res = memcpy_s(buf, length, buffer, length); + if (res != 0) { + return { false, nullptr }; + } + len = length; + + return { true, static_cast(obj) }; +} + +std::tuple TypeConverter::ToAniStringList( + ani_env *env, const std::string strList[], const uint32_t length) +{ + if (env == nullptr) { + return { false, nullptr }; + } + + auto classDesc = BuiltInTypes::String::classDesc.c_str(); + ani_array_ref result = nullptr; + ani_class cls = nullptr; + if (env->FindClass(classDesc, &cls) != ANI_OK) { + return { false, result }; + } + if (env->Array_New_Ref(cls, length, nullptr, &result) != ANI_OK) { + return { false, result }; + } + for (uint32_t i = 0; i < length; i++) { + auto [ret, item] = TypeConverter::ToAniString(env, strList[i]); + if (!ret) { + return { false, nullptr }; + } + + if (env->Array_Set_Ref(result, i, item) != ANI_OK) { + return { false, nullptr }; + } + } + return { true, result }; +} + +} // namespace OHOS::FileManagement::ModuleFileIO::ANI \ No newline at end of file diff --git a/interfaces/kits/js/src/common/ani_helper/type_converter.h b/interfaces/kits/js/src/common/ani_helper/type_converter.h new file mode 100644 index 0000000000000000000000000000000000000000..c5bf1fea1ef184bef7c1c9e9866cf696112893fd --- /dev/null +++ b/interfaces/kits/js/src/common/ani_helper/type_converter.h @@ -0,0 +1,48 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef INTERFACES_KITS_JS_SRC_COMMON_ANI_HELPER_TYPE_CONVERTER_H +#define INTERFACES_KITS_JS_SRC_COMMON_ANI_HELPER_TYPE_CONVERTER_H + +#include +#include + +#include + +#include "fs_array_buffer.h" +#include "fs_utils.h" + +namespace OHOS::FileManagement::ModuleFileIO::ANI { +inline const std::string EMPTY_STRING = ""; + +class TypeConverter { +public: + static std::tuple ToUTF8String(ani_env *env, const ani_string &path); + static std::tuple> ToOptionalInt32(ani_env *env, const ani_object &value); + static std::tuple> ToOptionalInt64(ani_env *env, const ani_object &value); + static std::tuple ToAniArrayBuffer(ani_env *env, void *buffer, size_t length); + static std::tuple ToAniString(ani_env *env, std::string str); + static std::tuple ToAniString(ani_env *env, std::string str, size_t size); + static std::tuple ToAniString(ani_env *env, const char *str); + static std::tuple> EnumToInt32(ani_env *env, const ani_enum_item &enumOp); + static std::tuple ToFileInfo(ani_env *env, const ani_object &pathOrFd); + static std::tuple ToArrayBuffer(ani_env *env, ani_arraybuffer &buffer); + static std::tuple ToAniStringList( + ani_env *env, const std::string strList[], const uint32_t length); +}; + +} // namespace OHOS::FileManagement::ModuleFileIO::ANI + +#endif // INTERFACES_KITS_JS_SRC_COMMON_ANI_HELPER_TYPE_CONVERTER_H \ No newline at end of file diff --git a/interfaces/kits/js/src/common/file_helper/fd_guard.cpp b/interfaces/kits/js/src/common/file_helper/fd_guard.cpp index 6959b45a52f534f468561ff090199b2e3c5f8735..6ca489d3f6a19e81eec8f1cc029ec81ee87cfa04 100644 --- a/interfaces/kits/js/src/common/file_helper/fd_guard.cpp +++ b/interfaces/kits/js/src/common/file_helper/fd_guard.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -17,7 +17,7 @@ #include -#include "../log.h" +#include "log.h" namespace OHOS { namespace DistributedFS { diff --git a/interfaces/kits/js/src/common/fs_file_filter.h b/interfaces/kits/js/src/common/fs_file_filter.h new file mode 100644 index 0000000000000000000000000000000000000000..f16c178213255dd738a7c62d64419e0d7adf6271 --- /dev/null +++ b/interfaces/kits/js/src/common/fs_file_filter.h @@ -0,0 +1,117 @@ +/* + * Copyright (C) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef FS_FILE_FILTER_H +#define FS_FILE_FILTER_H + +#include +#include +#include + +namespace OHOS { +namespace FileManagement { +namespace ModuleFileIO { + +class FsFileFilter { +public: + FsFileFilter() = default; + ~FsFileFilter() = default; + + FsFileFilter(const FsFileFilter &filter) = default; + FsFileFilter &operator=(const FsFileFilter &filter) = default; + + void SetSuffix(const std::optional> &suffix) + { + suffix_ = std::move(suffix); + } + + const std::optional> &GetSuffix() const + { + return suffix_; + } + + void SetDisplayName(const std::optional> &displayName) + { + displayName_ = std::move(displayName); + } + + const std::optional> &GetDisplayName() const + { + return displayName_; + } + + void SetMimeType(const std::optional> &mimeType) + { + mimeType_ = std::move(mimeType); + } + + const std::optional> &GetMimeType() const + { + return mimeType_; + } + + void SetFileSizeOver(const std::optional &fileSizeOver) + { + fileSizeOver_ = std::move(fileSizeOver); + } + + const std::optional &GetFileSizeOver() const + { + return fileSizeOver_; + } + + void SetLastModifiedAfter(const std::optional &lastModifiedAfter) + { + lastModifiedAfter_ = std::move(lastModifiedAfter); + } + + const std::optional &GetLastModifiedAfter() const + { + return lastModifiedAfter_; + } + + void SetExcludeMedia(const bool &excludeMedia) + { + excludeMedia_ = excludeMedia; + } + + bool GetExcludeMedia() const + { + return excludeMedia_; + } + + void SetHasFilter(const bool &hasFilter) + { + hasFilter_ = hasFilter; + } + + bool GetHasFilter() const + { + return hasFilter_; + } + +private: + std::optional> suffix_ = std::nullopt; + std::optional> displayName_ = std::nullopt; + std::optional> mimeType_ = std::nullopt; + std::optional fileSizeOver_ = std::nullopt; + std::optional lastModifiedAfter_ = std::nullopt; + bool excludeMedia_ = false; + bool hasFilter_ = false; +}; + +} // namespace ModuleFileIO +} // namespace FileManagement +} // namespace OHOS +#endif // FS_FILE_FILTER_H \ No newline at end of file diff --git a/interfaces/kits/js/src/common/napi/n_async/n_async_context.h b/interfaces/kits/js/src/common/napi/n_async/n_async_context.h index 87339bbdddfdc837b658e60e7026f2bc10e6bdc7..0daf0d971262a2ded90bc92f02507c1c223ac701 100644 --- a/interfaces/kits/js/src/common/napi/n_async/n_async_context.h +++ b/interfaces/kits/js/src/common/napi/n_async/n_async_context.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -16,9 +16,9 @@ #ifndef N_ASYNC_CONTEXT_H #define N_ASYNC_CONTEXT_H -#include "../../uni_error.h" -#include "../n_val.h" #include "n_ref.h" +#include "n_val.h" +#include "uni_error.h" namespace OHOS { namespace DistributedFS { diff --git a/interfaces/kits/js/src/common/napi/n_async/n_async_work_callback.cpp b/interfaces/kits/js/src/common/napi/n_async/n_async_work_callback.cpp index 75136db63bd81f8e8864c21c924c5e105ab50406..c85f924502ba7c679a8fa7c88c67c1dbdf65a218 100644 --- a/interfaces/kits/js/src/common/napi/n_async/n_async_work_callback.cpp +++ b/interfaces/kits/js/src/common/napi/n_async/n_async_work_callback.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021-2023 Huawei Device Co., Ltd. + * Copyright (c) 2021-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -14,7 +14,7 @@ */ #include "n_async_work_callback.h" -#include "../../log.h" +#include "log.h" namespace OHOS { namespace DistributedFS { diff --git a/interfaces/kits/js/src/common/napi/n_async/n_async_work_promise.cpp b/interfaces/kits/js/src/common/napi/n_async/n_async_work_promise.cpp index 1ba6a0fdb0d2339bca96cfff86975fe37c4f2894..85883021cd0c57b926dc6ce6a7e5d1db20c3cef6 100644 --- a/interfaces/kits/js/src/common/napi/n_async/n_async_work_promise.cpp +++ b/interfaces/kits/js/src/common/napi/n_async/n_async_work_promise.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -14,7 +14,7 @@ */ #include "n_async_work_promise.h" -#include "../../log.h" +#include "log.h" namespace OHOS { namespace DistributedFS { diff --git a/interfaces/kits/js/src/common/napi/n_async/n_ref.h b/interfaces/kits/js/src/common/napi/n_async/n_ref.h index a9f166cfc50cc5f2e6920711c4a57da2ba0db4ed..e66ef78503b40606065d9c4a904399936a0bcdae 100644 --- a/interfaces/kits/js/src/common/napi/n_async/n_ref.h +++ b/interfaces/kits/js/src/common/napi/n_async/n_ref.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -16,7 +16,7 @@ #ifndef N_REF_H #define N_REF_H -#include "../n_val.h" +#include "n_val.h" namespace OHOS { namespace DistributedFS { diff --git a/interfaces/kits/js/src/common/napi/n_class.cpp b/interfaces/kits/js/src/common/napi/n_class.cpp index 191fefc0de2694d4329c5565d53f77f15b3306a6..8e4c08d284e656497aae77de4460826a04e1132a 100644 --- a/interfaces/kits/js/src/common/napi/n_class.cpp +++ b/interfaces/kits/js/src/common/napi/n_class.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -18,7 +18,7 @@ #include #include -#include "../log.h" +#include "log.h" namespace OHOS { namespace DistributedFS { diff --git a/interfaces/kits/js/src/common/napi/n_class.h b/interfaces/kits/js/src/common/napi/n_class.h index 171b7f6274f693ada55a823a82e2c68b19d14466..9296468bd7ab0515970ae98b13fdc6e3136efd9f 100644 --- a/interfaces/kits/js/src/common/napi/n_class.h +++ b/interfaces/kits/js/src/common/napi/n_class.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -16,11 +16,10 @@ #ifndef INTERFACES_KITS_JS_SRC_COMMON_NAPI_N_CLASS_H #define INTERFACES_KITS_JS_SRC_COMMON_NAPI_N_CLASS_H -#include "uni_header.h" - #include -#include "../log.h" +#include "log.h" +#include "uni_header.h" namespace OHOS { namespace DistributedFS { diff --git a/interfaces/kits/js/src/common/napi/n_func_arg.cpp b/interfaces/kits/js/src/common/napi/n_func_arg.cpp index aa2cc60c758337a8a1fa9eb799732713b22c8c5f..ab80b1c598cdf0a1a66a78b969931d59167fe438 100644 --- a/interfaces/kits/js/src/common/napi/n_func_arg.cpp +++ b/interfaces/kits/js/src/common/napi/n_func_arg.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -15,7 +15,7 @@ #include "n_func_arg.h" -#include "../log.h" +#include "log.h" namespace OHOS { namespace DistributedFS { diff --git a/interfaces/kits/js/src/common/napi/n_val.cpp b/interfaces/kits/js/src/common/napi/n_val.cpp index a0b7fe6e060c70a76e14abf81d99e12f71e77a20..2f739931978520f7e634f44077d0a7e500a3eb0a 100644 --- a/interfaces/kits/js/src/common/napi/n_val.cpp +++ b/interfaces/kits/js/src/common/napi/n_val.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021-2022 Huawei Device Co., Ltd. + * Copyright (c) 2021-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -17,8 +17,8 @@ #include -#include "../log.h" -#include "../uni_error.h" +#include "log.h" +#include "uni_error.h" namespace OHOS { namespace DistributedFS { diff --git a/interfaces/kits/js/src/mod_document/document_n_exporter.cpp b/interfaces/kits/js/src/mod_document/document_n_exporter.cpp index a23741bc796a91bd97accd0fe451aa6ebe8ffed6..d2eb2d14ac90ba0891e17a3404735767b49c1abc 100644 --- a/interfaces/kits/js/src/mod_document/document_n_exporter.cpp +++ b/interfaces/kits/js/src/mod_document/document_n_exporter.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021-2022 Huawei Device Co., Ltd. + * Copyright (c) 2021-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -15,15 +15,15 @@ #include "document_n_exporter.h" -#include #include +#include -#include "../common/napi/n_async/n_async_work_callback.h" -#include "../common/napi/n_async/n_async_work_promise.h" -#include "../common/napi/n_class.h" -#include "../common/napi/n_func_arg.h" -#include "../common/napi/n_val.h" -#include "../common/uni_error.h" +#include "n_async_work_callback.h" +#include "n_async_work_promise.h" +#include "n_class.h" +#include "n_func_arg.h" +#include "n_val.h" +#include "uni_error.h" namespace OHOS { namespace DistributedFS { diff --git a/interfaces/kits/js/src/mod_document/document_n_exporter.h b/interfaces/kits/js/src/mod_document/document_n_exporter.h index 653e1e6c7b2017863358e6ed8ab7bd1bffa9afb0..10bd380102d2cda917b3f33b2fd8c58fb8e42365 100644 --- a/interfaces/kits/js/src/mod_document/document_n_exporter.h +++ b/interfaces/kits/js/src/mod_document/document_n_exporter.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -16,7 +16,7 @@ #ifndef DOCUMENT_N_EXPORTER_H #define DOCUMENT_N_EXPORTER_H -#include "../common/napi/n_exporter.h" +#include "n_exporter.h" namespace OHOS { namespace DistributedFS { diff --git a/interfaces/kits/js/src/mod_file/class_file/file_n_exporter.cpp b/interfaces/kits/js/src/mod_file/class_file/file_n_exporter.cpp index 01f591e74928233f30d421f2474786e3aa46a53b..46fdb198ef3db3a350a53669f0bbe613e6fac004 100644 --- a/interfaces/kits/js/src/mod_file/class_file/file_n_exporter.cpp +++ b/interfaces/kits/js/src/mod_file/class_file/file_n_exporter.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -26,17 +26,18 @@ #include #include #include +#include + #include #include -#include -#include "../../common/ability_helper.h" -#include "../../common/file_helper/fd_guard.h" -#include "../../common/napi/n_class.h" -#include "../../common/napi/n_func_arg.h" -#include "../../common/napi/n_val.h" -#include "../../common/uni_error.h" -#include "../common_func.h" +#include "ability_helper.h" +#include "common_func.h" +#include "fd_guard.h" +#include "n_class.h" +#include "n_func_arg.h" +#include "n_val.h" +#include "uni_error.h" namespace OHOS { namespace DistributedFS { diff --git a/interfaces/kits/js/src/mod_file/class_file/file_n_exporter.h b/interfaces/kits/js/src/mod_file/class_file/file_n_exporter.h index f39a8069ea84c2e58d15649705fd7fe6fd626a51..dc5434cd9b30e1af5b8efe4995314ca60e9f4f29 100644 --- a/interfaces/kits/js/src/mod_file/class_file/file_n_exporter.h +++ b/interfaces/kits/js/src/mod_file/class_file/file_n_exporter.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021-2022 Huawei Device Co., Ltd. + * Copyright (c) 2021-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -16,7 +16,7 @@ #ifndef INTERFACES_KITS_JS_SRC_MOD_FILE_CLASS_FILE_FILE_N_EXPORTER_H #define INTERFACES_KITS_JS_SRC_MOD_FILE_CLASS_FILE_FILE_N_EXPORTER_H -#include "../../common/napi/n_exporter.h" +#include "n_exporter.h" namespace OHOS { namespace DistributedFS { diff --git a/interfaces/kits/js/src/mod_file/common_func.cpp b/interfaces/kits/js/src/mod_file/common_func.cpp index 4a9fa3d399a5552adb98a1ff64d32c852a96ad7e..73f52d935f3b35edfafc366ebb48390162da79bb 100644 --- a/interfaces/kits/js/src/mod_file/common_func.cpp +++ b/interfaces/kits/js/src/mod_file/common_func.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021-2022 Huawei Device Co., Ltd. + * Copyright (c) 2021-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -15,7 +15,7 @@ #include "common_func.h" -#include "../common/napi/n_func_arg.h" +#include "n_func_arg.h" namespace OHOS { namespace DistributedFS { diff --git a/interfaces/kits/js/src/mod_file/common_func.h b/interfaces/kits/js/src/mod_file/common_func.h index 207411602e2346198b7edc1aae12e0ae06f0f160..85ac917257048ce2fe5fedc160451a68b085aeda 100644 --- a/interfaces/kits/js/src/mod_file/common_func.h +++ b/interfaces/kits/js/src/mod_file/common_func.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021-2022 Huawei Device Co., Ltd. + * Copyright (c) 2021-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -16,7 +16,7 @@ #ifndef INTERFACES_KITS_JS_SRC_MOD_FILE_COMMON_FUNC_H #define INTERFACES_KITS_JS_SRC_MOD_FILE_COMMON_FUNC_H -#include "../common/napi/n_val.h" +#include "n_val.h" namespace OHOS { namespace DistributedFS { diff --git a/interfaces/kits/js/src/mod_file/module.cpp b/interfaces/kits/js/src/mod_file/module.cpp index b4588cf4525f7fc744eb2a78c62d81149e98d93b..1aba9024bbebed791c0801b747ac914ca3c6265a 100644 --- a/interfaces/kits/js/src/mod_file/module.cpp +++ b/interfaces/kits/js/src/mod_file/module.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -16,8 +16,8 @@ #include #include -#include "../common/log.h" #include "class_file/file_n_exporter.h" +#include "log.h" using namespace std; diff --git a/interfaces/kits/js/src/mod_fileio/class_constants/constants.cpp b/interfaces/kits/js/src/mod_fileio/class_constants/constants.cpp index f046d8e849d58b86c07cab27d068a227cbb98b86..c557acfe3c3c18eeaadf103be53fa93e8d6b4a1d 100644 --- a/interfaces/kits/js/src/mod_fileio/class_constants/constants.cpp +++ b/interfaces/kits/js/src/mod_fileio/class_constants/constants.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021-2022 Huawei Device Co., Ltd. + * Copyright (c) 2021-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -21,14 +21,15 @@ #include #include #include -#include #include +#include + +#include "log.h" +#include "n_class.h" +#include "n_func_arg.h" #include "securec.h" -#include "../../common/log.h" -#include "../../common/napi/n_class.h" -#include "../../common/napi/n_func_arg.h" -#include "../../common/uni_error.h" +#include "uni_error.h" namespace OHOS { namespace DistributedFS { diff --git a/interfaces/kits/js/src/mod_fileio/class_constants/constants.h b/interfaces/kits/js/src/mod_fileio/class_constants/constants.h index 59da2b0bf163f856963990cedf983721269e9a13..f42aacf7365dd301054c47b11fb7b73ac7c6bc9e 100644 --- a/interfaces/kits/js/src/mod_fileio/class_constants/constants.h +++ b/interfaces/kits/js/src/mod_fileio/class_constants/constants.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021-2022 Huawei Device Co., Ltd. + * Copyright (c) 2021-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -16,7 +16,7 @@ #ifndef INTERFACES_KITS_JS_SRC_MOD_FILEIO_CLASS_CONSTANTS_CONSTANTS_H #define INTERFACES_KITS_JS_SRC_MOD_FILEIO_CLASS_CONSTANTS_CONSTANTS_H -#include "../../common/napi/n_exporter.h" +#include "n_exporter.h" namespace OHOS { namespace DistributedFS { diff --git a/interfaces/kits/js/src/mod_fileio/class_dir/dir_n_exporter.cpp b/interfaces/kits/js/src/mod_fileio/class_dir/dir_n_exporter.cpp index ae1339bd53f3aa189daf397d5228e6fe2ba2953f..d1c4b319e9d584a65b699d48eff7de9f14dc0d23 100644 --- a/interfaces/kits/js/src/mod_fileio/class_dir/dir_n_exporter.cpp +++ b/interfaces/kits/js/src/mod_fileio/class_dir/dir_n_exporter.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021-2022 Huawei Device Co., Ltd. + * Copyright (c) 2021-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -21,15 +21,15 @@ #include #include +#include "class_dirent/dirent_entity.h" +#include "class_dirent/dirent_n_exporter.h" +#include "common_func.h" #include "dir_entity.h" +#include "n_async_work_callback.h" +#include "n_async_work_promise.h" +#include "n_class.h" +#include "n_func_arg.h" #include "securec.h" -#include "../../common/napi/n_async/n_async_work_callback.h" -#include "../../common/napi/n_async/n_async_work_promise.h" -#include "../../common/napi/n_class.h" -#include "../../common/napi/n_func_arg.h" -#include "../class_dirent/dirent_entity.h" -#include "../class_dirent/dirent_n_exporter.h" -#include "../common_func.h" namespace OHOS { namespace DistributedFS { diff --git a/interfaces/kits/js/src/mod_fileio/class_dir/dir_n_exporter.h b/interfaces/kits/js/src/mod_fileio/class_dir/dir_n_exporter.h index a40ed03d2b542f5ef501fdd4cd3c922bae2d2e2f..0ecc22ee90b540325063490af1d570e4f2f684df 100644 --- a/interfaces/kits/js/src/mod_fileio/class_dir/dir_n_exporter.h +++ b/interfaces/kits/js/src/mod_fileio/class_dir/dir_n_exporter.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021-2022 Huawei Device Co., Ltd. + * Copyright (c) 2021-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -18,7 +18,7 @@ #include -#include "../../common/napi/n_exporter.h" +#include "n_exporter.h" namespace OHOS { namespace DistributedFS { diff --git a/interfaces/kits/js/src/mod_fileio/class_dirent/dirent_n_exporter.cpp b/interfaces/kits/js/src/mod_fileio/class_dirent/dirent_n_exporter.cpp index 29b78ca89dfc802e8130b98dd113c92424b9103d..745ade32bde1c30f4bd15e0f65bb5cfd797d5f22 100644 --- a/interfaces/kits/js/src/mod_fileio/class_dirent/dirent_n_exporter.cpp +++ b/interfaces/kits/js/src/mod_fileio/class_dirent/dirent_n_exporter.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021-2022 Huawei Device Co., Ltd. + * Copyright (c) 2021-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -21,13 +21,13 @@ #include #include -#include "securec.h" -#include "../../common/log.h" -#include "../../common/napi/n_class.h" -#include "../../common/napi/n_func_arg.h" -#include "../../common/uni_error.h" -#include "../common_func.h" +#include "common_func.h" #include "dirent_entity.h" +#include "log.h" +#include "n_class.h" +#include "n_func_arg.h" +#include "securec.h" +#include "uni_error.h" namespace OHOS { namespace DistributedFS { diff --git a/interfaces/kits/js/src/mod_fileio/class_dirent/dirent_n_exporter.h b/interfaces/kits/js/src/mod_fileio/class_dirent/dirent_n_exporter.h index 0f60629e09429656f044da1090fa5974c116b994..0584f2a5b8e8f46a645df952e992144819999498 100644 --- a/interfaces/kits/js/src/mod_fileio/class_dirent/dirent_n_exporter.h +++ b/interfaces/kits/js/src/mod_fileio/class_dirent/dirent_n_exporter.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -16,7 +16,7 @@ #ifndef INTERFACES_KITS_JS_SRC_MOD_FILEIO_CLASS_DIRENT_DIRENT_N_EXPORTER_H #define INTERFACES_KITS_JS_SRC_MOD_FILEIO_CLASS_DIRENT_DIRENT_N_EXPORTER_H -#include "../../common/napi/n_exporter.h" +#include "n_exporter.h" namespace OHOS { namespace DistributedFS { diff --git a/interfaces/kits/js/src/mod_fileio/class_file/file_entity.h b/interfaces/kits/js/src/mod_fileio/class_file/file_entity.h index 9a82a6f7900f8364a6a5cedc98794a94ac5a0516..8737c5d1055fc69bc7469d4b44f1fd6dd4c934d9 100644 --- a/interfaces/kits/js/src/mod_fileio/class_file/file_entity.h +++ b/interfaces/kits/js/src/mod_fileio/class_file/file_entity.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 Huawei Device Co., Ltd. + * Copyright (c) 2022-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -18,7 +18,7 @@ #include -#include "../../common/file_helper/fd_guard.h" +#include "file_helper/fd_guard.h" namespace OHOS { namespace DistributedFS { diff --git a/interfaces/kits/js/src/mod_fileio/class_file/file_n_exporter.cpp b/interfaces/kits/js/src/mod_fileio/class_file/file_n_exporter.cpp index 4eeb63358e881794c575b497ff2618a236cf0553..7946542fd5e5b2c86881ce3b0fd7d329c4f6235a 100644 --- a/interfaces/kits/js/src/mod_fileio/class_file/file_n_exporter.cpp +++ b/interfaces/kits/js/src/mod_fileio/class_file/file_n_exporter.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 Huawei Device Co., Ltd. + * Copyright (c) 2022-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -20,14 +20,14 @@ #include #include -#include "../../common/log.h" -#include "../../common/napi/n_async/n_async_work_callback.h" -#include "../../common/napi/n_async/n_async_work_promise.h" -#include "../../common/napi/n_class.h" -#include "../../common/napi/n_func_arg.h" -#include "../../common/uni_error.h" -#include "../common_func.h" +#include "common_func.h" #include "file_entity.h" +#include "log.h" +#include "n_async_work_callback.h" +#include "n_async_work_promise.h" +#include "n_class.h" +#include "n_func_arg.h" +#include "uni_error.h" namespace OHOS { namespace DistributedFS { diff --git a/interfaces/kits/js/src/mod_fileio/class_file/file_n_exporter.h b/interfaces/kits/js/src/mod_fileio/class_file/file_n_exporter.h index c77716e6123e00726a32d35851e0383bd047b8a1..4a7b85a2b7c7edfbe38a3e4c539939e005f1b5cb 100644 --- a/interfaces/kits/js/src/mod_fileio/class_file/file_n_exporter.h +++ b/interfaces/kits/js/src/mod_fileio/class_file/file_n_exporter.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 Huawei Device Co., Ltd. + * Copyright (c) 2022-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -16,7 +16,7 @@ #ifndef INTERFACES_KITS_JS_SRC_MOD_FILEIO_CLASS_FILE_FILE_N_EXPORTER_H #define INTERFACES_KITS_JS_SRC_MOD_FILEIO_CLASS_FILE_FILE_N_EXPORTER_H -#include "../../common/napi/n_exporter.h" +#include "n_exporter.h" namespace OHOS { namespace DistributedFS { diff --git a/interfaces/kits/js/src/mod_fileio/class_stat/stat_n_exporter.cpp b/interfaces/kits/js/src/mod_fileio/class_stat/stat_n_exporter.cpp index 40c0ca18fe2db64a90095e06c124124224938b3b..b80b1bd4717bcf79d29994441ebb3f79b517bd70 100644 --- a/interfaces/kits/js/src/mod_fileio/class_stat/stat_n_exporter.cpp +++ b/interfaces/kits/js/src/mod_fileio/class_stat/stat_n_exporter.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021-2022 Huawei Device Co., Ltd. + * Copyright (c) 2021-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -21,14 +21,14 @@ #include #include +#include "log.h" +#include "n_async_work_callback.h" +#include "n_async_work_promise.h" +#include "n_class.h" +#include "n_func_arg.h" #include "securec.h" -#include "../../common/log.h" -#include "../../common/napi/n_async/n_async_work_callback.h" -#include "../../common/napi/n_async/n_async_work_promise.h" -#include "../../common/napi/n_class.h" -#include "../../common/napi/n_func_arg.h" -#include "../../common/uni_error.h" #include "stat_entity.h" +#include "uni_error.h" namespace OHOS { namespace DistributedFS { diff --git a/interfaces/kits/js/src/mod_fileio/class_stat/stat_n_exporter.h b/interfaces/kits/js/src/mod_fileio/class_stat/stat_n_exporter.h index 4304856649cc81f9e6b455207e98a3f1dc6b208b..966df112b97d64da4706f4f2a53717b316d5a90e 100644 --- a/interfaces/kits/js/src/mod_fileio/class_stat/stat_n_exporter.h +++ b/interfaces/kits/js/src/mod_fileio/class_stat/stat_n_exporter.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -16,7 +16,7 @@ #ifndef INTERFACES_KITS_JS_SRC_MOD_FILEIO_CLASS_STAT_N_EXPORTER_H #define INTERFACES_KITS_JS_SRC_MOD_FILEIO_CLASS_STAT_N_EXPORTER_H -#include "../../common/napi/n_exporter.h" +#include "n_exporter.h" namespace OHOS { namespace DistributedFS { diff --git a/interfaces/kits/js/src/mod_fileio/class_stat_v9/stat_n_exporter_v9.cpp b/interfaces/kits/js/src/mod_fileio/class_stat_v9/stat_n_exporter_v9.cpp index fb2768f698b00b72d525ed2108c7fa2e1b354d1e..856cc3ee9e7163dba149e855c55eab3c3b86254d 100644 --- a/interfaces/kits/js/src/mod_fileio/class_stat_v9/stat_n_exporter_v9.cpp +++ b/interfaces/kits/js/src/mod_fileio/class_stat_v9/stat_n_exporter_v9.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022-2023 Huawei Device Co., Ltd. + * Copyright (c) 2022-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -14,8 +14,6 @@ */ #include "stat_n_exporter_v9.h" -#include "../../common/napi/n_async/n_async_work_callback.h" -#include "../../common/napi/n_async/n_async_work_promise.h" #include #include @@ -23,13 +21,14 @@ #include #include +#include "log.h" +#include "n_async_work_callback.h" +#include "n_async_work_promise.h" +#include "n_class.h" +#include "n_func_arg.h" #include "securec.h" - -#include "../../common/log.h" -#include "../../common/napi/n_class.h" -#include "../../common/napi/n_func_arg.h" -#include "../../common/uni_error.h" #include "stat_entity_v9.h" +#include "uni_error.h" namespace OHOS { namespace DistributedFS { diff --git a/interfaces/kits/js/src/mod_fileio/class_stat_v9/stat_n_exporter_v9.h b/interfaces/kits/js/src/mod_fileio/class_stat_v9/stat_n_exporter_v9.h index c686e3d86b7a1255b627a20aeaa94c97fd6cc0ba..4b7d74087c850cd7a61a0d92728674d0a4d850d7 100644 --- a/interfaces/kits/js/src/mod_fileio/class_stat_v9/stat_n_exporter_v9.h +++ b/interfaces/kits/js/src/mod_fileio/class_stat_v9/stat_n_exporter_v9.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 Huawei Device Co., Ltd. + * Copyright (c) 2022-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -16,7 +16,7 @@ #ifndef INTERFACES_KITS_JS_SRC_MOD_FILEIO_CLASS_STAT_N_EXPORTER_V9_H #define INTERFACES_KITS_JS_SRC_MOD_FILEIO_CLASS_STAT_N_EXPORTER_V9_H -#include "../../common/napi/n_exporter.h" +#include "n_exporter.h" namespace OHOS { namespace DistributedFS { diff --git a/interfaces/kits/js/src/mod_fileio/class_stream/flush.cpp b/interfaces/kits/js/src/mod_fileio/class_stream/flush.cpp index 590b47e95eea7e25a8e5c85fa91c23764ca2300c..13bbe13c9768a9786be0c79110fc1f155aeb8495 100644 --- a/interfaces/kits/js/src/mod_fileio/class_stream/flush.cpp +++ b/interfaces/kits/js/src/mod_fileio/class_stream/flush.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -17,15 +17,14 @@ #include #include -#include "../../common/napi/n_async/n_async_work_callback.h" -#include "../../common/napi/n_async/n_async_work_promise.h" -#include "../../common/napi/n_class.h" -#include "../../common/napi/n_func_arg.h" -#include "../../common/napi/n_val.h" -#include "../../common/uni_error.h" - -#include "../class_stat/stat_entity.h" -#include "../class_stat/stat_n_exporter.h" +#include "class_stat/stat_entity.h" +#include "class_stat/stat_n_exporter.h" +#include "n_async_work_callback.h" +#include "n_async_work_promise.h" +#include "n_class.h" +#include "n_func_arg.h" +#include "n_val.h" +#include "uni_error.h" namespace OHOS { namespace DistributedFS { diff --git a/interfaces/kits/js/src/mod_fileio/class_stream/flush.h b/interfaces/kits/js/src/mod_fileio/class_stream/flush.h index c616571b3f8c3435cbb0ea2bd336661f18bff024..969a29c8dfd950c32bf268dc121100247b6c80ab 100644 --- a/interfaces/kits/js/src/mod_fileio/class_stream/flush.h +++ b/interfaces/kits/js/src/mod_fileio/class_stream/flush.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -16,7 +16,7 @@ #ifndef INTERFACES_KITS_JS_SRC_MOD_FILEIO_CLASS_STREAM_FLUSH_H #define INTERFACES_KITS_JS_SRC_MOD_FILEIO_CLASS_STREAM_FLUSH_H -#include "../../common/napi/uni_header.h" +#include "uni_header.h" namespace OHOS { namespace DistributedFS { diff --git a/interfaces/kits/js/src/mod_fileio/class_stream/stream_n_exporter.cpp b/interfaces/kits/js/src/mod_fileio/class_stream/stream_n_exporter.cpp index 611dcfc3d4275718ce66e99a1a265ec6bbea6c42..b27d6a71e2a49c669765a903b015cb62850bc1bf 100644 --- a/interfaces/kits/js/src/mod_fileio/class_stream/stream_n_exporter.cpp +++ b/interfaces/kits/js/src/mod_fileio/class_stream/stream_n_exporter.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021-2022 Huawei Device Co., Ltd. + * Copyright (c) 2021-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -21,17 +21,17 @@ #include #include #include + +#include "common_func.h" #include "flush.h" +#include "log.h" +#include "n_async_work_callback.h" +#include "n_async_work_promise.h" +#include "n_class.h" +#include "n_func_arg.h" #include "securec.h" - -#include "../../common/log.h" -#include "../../common/napi/n_async/n_async_work_callback.h" -#include "../../common/napi/n_async/n_async_work_promise.h" -#include "../../common/napi/n_class.h" -#include "../../common/napi/n_func_arg.h" -#include "../../common/uni_error.h" -#include "../common_func.h" #include "stream_entity.h" +#include "uni_error.h" namespace OHOS { namespace DistributedFS { diff --git a/interfaces/kits/js/src/mod_fileio/class_stream/stream_n_exporter.h b/interfaces/kits/js/src/mod_fileio/class_stream/stream_n_exporter.h index 3cfe4d2d204f21f3481e4518094bae338f7bede8..4f00cd6d5ba17d41ac9ee289380460c596f42edd 100644 --- a/interfaces/kits/js/src/mod_fileio/class_stream/stream_n_exporter.h +++ b/interfaces/kits/js/src/mod_fileio/class_stream/stream_n_exporter.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -16,7 +16,7 @@ #ifndef INTERFACES_KITS_JS_SRC_MOD_FILEIO_CLASS_STREAM_STREAM_N_EXPORTER_H #define INTERFACES_KITS_JS_SRC_MOD_FILEIO_CLASS_STREAM_STREAM_N_EXPORTER_H -#include "../../common/napi/n_exporter.h" +#include "n_exporter.h" namespace OHOS { namespace DistributedFS { diff --git a/interfaces/kits/js/src/mod_fileio/class_watcher/watcher_entity.h b/interfaces/kits/js/src/mod_fileio/class_watcher/watcher_entity.h index ce604ee6b042eb0159ba61ad0bd1fd0251c9ebbb..716c66b685148e033572955f283e5268493c43a5 100644 --- a/interfaces/kits/js/src/mod_fileio/class_watcher/watcher_entity.h +++ b/interfaces/kits/js/src/mod_fileio/class_watcher/watcher_entity.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -18,7 +18,7 @@ #include -#include "../../common/napi/uni_header.h" +#include "uni_header.h" namespace OHOS { namespace DistributedFS { diff --git a/interfaces/kits/js/src/mod_fileio/class_watcher/watcher_n_exporter.cpp b/interfaces/kits/js/src/mod_fileio/class_watcher/watcher_n_exporter.cpp index 2947b10cb50e5d108cb3d81e27eb5ee9e53f8274..360d1574a9f070ff9f6604b54ea3c20b7eef0660 100644 --- a/interfaces/kits/js/src/mod_fileio/class_watcher/watcher_n_exporter.cpp +++ b/interfaces/kits/js/src/mod_fileio/class_watcher/watcher_n_exporter.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -20,13 +20,13 @@ #include #include -#include "../../common/log.h" -#include "../../common/napi/n_async/n_async_work_callback.h" -#include "../../common/napi/n_async/n_async_work_promise.h" -#include "../../common/napi/n_class.h" -#include "../../common/napi/n_func_arg.h" -#include "../../common/uni_error.h" +#include "log.h" +#include "n_async_work_callback.h" +#include "n_async_work_promise.h" +#include "n_class.h" +#include "n_func_arg.h" #include "securec.h" +#include "uni_error.h" #include "watcher_entity.h" namespace OHOS { diff --git a/interfaces/kits/js/src/mod_fileio/class_watcher/watcher_n_exporter.h b/interfaces/kits/js/src/mod_fileio/class_watcher/watcher_n_exporter.h index 3d3502b7babfd5d7c3037cb51d1aee7e1ffa845a..13c648ef7d58a11871a23819f2c8d8fbaa1657d8 100644 --- a/interfaces/kits/js/src/mod_fileio/class_watcher/watcher_n_exporter.h +++ b/interfaces/kits/js/src/mod_fileio/class_watcher/watcher_n_exporter.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -16,7 +16,7 @@ #ifndef INTERFACES_KITS_JS_SRC_MOD_FILEIO_CLASS_WATCHER_WATCHER_N_EXPORTER_H #define INTERFACES_KITS_JS_SRC_MOD_FILEIO_CLASS_WATCHER_WATCHER_N_EXPORTER_H -#include "../../common/napi/n_exporter.h" +#include "n_exporter.h" namespace OHOS { namespace DistributedFS { diff --git a/interfaces/kits/js/src/mod_fileio/common_func.cpp b/interfaces/kits/js/src/mod_fileio/common_func.cpp index b29b270eba3048ee7e0fa791e5a5a1d38f453b1d..8df8b02dd1da15ae040f8c3ec3f63f54dc203359 100644 --- a/interfaces/kits/js/src/mod_fileio/common_func.cpp +++ b/interfaces/kits/js/src/mod_fileio/common_func.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021-2022 Huawei Device Co., Ltd. + * Copyright (c) 2021-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -17,15 +17,16 @@ #include #include +#include + #include #include -#include -#include "../common/log.h" -#include "../common/napi/n_class.h" -#include "../common/napi/n_func_arg.h" -#include "../common/napi/n_val.h" -#include "../common/uni_error.h" +#include "log.h" +#include "n_class.h" +#include "n_func_arg.h" +#include "n_val.h" +#include "uni_error.h" namespace OHOS { namespace DistributedFS { diff --git a/interfaces/kits/js/src/mod_fileio/common_func.h b/interfaces/kits/js/src/mod_fileio/common_func.h index b76ad5469024a1030ae81bd835029f9cd02cd72e..37ee34cc5bf6f921b2fef75b8234beb64849ce35 100644 --- a/interfaces/kits/js/src/mod_fileio/common_func.h +++ b/interfaces/kits/js/src/mod_fileio/common_func.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021-2022 Huawei Device Co., Ltd. + * Copyright (c) 2021-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -16,7 +16,7 @@ #ifndef INTERFACES_KITS_JS_SRC_MOD_FILEIO_COMMON_FUNC_H #define INTERFACES_KITS_JS_SRC_MOD_FILEIO_COMMON_FUNC_H -#include "../common/napi/uni_header.h" +#include "uni_header.h" namespace OHOS { namespace DistributedFS { diff --git a/interfaces/kits/js/src/mod_fileio/module.cpp b/interfaces/kits/js/src/mod_fileio/module.cpp index 536e84e7555ae1027b411c8b7abd10f2d579d475..0f5f12fd178b477f57a49d54433d7d7f9e16505f 100644 --- a/interfaces/kits/js/src/mod_fileio/module.cpp +++ b/interfaces/kits/js/src/mod_fileio/module.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021-2022 Huawei Device Co., Ltd. + * Copyright (c) 2021-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -16,13 +16,13 @@ #include #include -#include "../common/log.h" #include "class_constants/constants.h" #include "class_dir/dir_n_exporter.h" #include "class_dirent/dirent_n_exporter.h" #include "class_stat/stat_n_exporter.h" #include "class_stream/stream_n_exporter.h" #include "class_watcher/watcher_n_exporter.h" +#include "log.h" #include "properties/prop_n_exporter.h" using namespace std; diff --git a/interfaces/kits/js/src/mod_fileio/module_v9.cpp b/interfaces/kits/js/src/mod_fileio/module_v9.cpp index e1f412037e993d688f6ee045e01c6b0b22a45ea9..ca928065568c5364006b9ac3761edbc7e9aa1881 100644 --- a/interfaces/kits/js/src/mod_fileio/module_v9.cpp +++ b/interfaces/kits/js/src/mod_fileio/module_v9.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 Huawei Device Co., Ltd. + * Copyright (c) 2022-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -16,10 +16,10 @@ #include #include -#include "../common/log.h" #include "class_file/file_n_exporter.h" #include "class_stat_v9/stat_n_exporter_v9.h" #include "common_func.h" +#include "log.h" #include "properties/prop_n_exporter_v9.h" using namespace std; diff --git a/interfaces/kits/js/src/mod_fileio/properties/chmod.cpp b/interfaces/kits/js/src/mod_fileio/properties/chmod.cpp index adcce280de289333bec5ccb4a7f82f32a32eaca7..5d851ddc14d2c7dfc492a57b4947ce98012bc869 100644 --- a/interfaces/kits/js/src/mod_fileio/properties/chmod.cpp +++ b/interfaces/kits/js/src/mod_fileio/properties/chmod.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021-2022 Huawei Device Co., Ltd. + * Copyright (c) 2021-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -16,13 +16,14 @@ #include "chmod.h" #include -#include #include #include -#include "../../common/napi/n_async/n_async_work_callback.h" -#include "../../common/napi/n_async/n_async_work_promise.h" -#include "../../common/napi/n_func_arg.h" +#include + +#include "n_async_work_callback.h" +#include "n_async_work_promise.h" +#include "n_func_arg.h" namespace OHOS { namespace DistributedFS { diff --git a/interfaces/kits/js/src/mod_fileio/properties/chmod.h b/interfaces/kits/js/src/mod_fileio/properties/chmod.h index 825289198b788ae310362e2850ff1e508e4dfe4f..c46cf4446d8eabd474232add667cc755c1922337 100644 --- a/interfaces/kits/js/src/mod_fileio/properties/chmod.h +++ b/interfaces/kits/js/src/mod_fileio/properties/chmod.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -16,7 +16,7 @@ #ifndef INTERFACES_KITS_JS_SRC_MOD_FILEIO_PROPERTIES_CHMOD_H #define INTERFACES_KITS_JS_SRC_MOD_FILEIO_PROPERTIES_CHMOD_H -#include "../../common/napi/n_val.h" +#include "n_val.h" namespace OHOS { namespace DistributedFS { diff --git a/interfaces/kits/js/src/mod_fileio/properties/chown.cpp b/interfaces/kits/js/src/mod_fileio/properties/chown.cpp index f8ed0df9d70f2638ce5853bff68b2c848f723e84..ded9bf0220096b9895577c220c4bc0b5b62e1d65 100644 --- a/interfaces/kits/js/src/mod_fileio/properties/chown.cpp +++ b/interfaces/kits/js/src/mod_fileio/properties/chown.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021-2022 Huawei Device Co., Ltd. + * Copyright (c) 2021-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -19,9 +19,9 @@ #include #include -#include "../../common/napi/n_async/n_async_work_callback.h" -#include "../../common/napi/n_async/n_async_work_promise.h" -#include "../../common/napi/n_func_arg.h" +#include "n_async_work_callback.h" +#include "n_async_work_promise.h" +#include "n_func_arg.h" namespace OHOS { namespace DistributedFS { diff --git a/interfaces/kits/js/src/mod_fileio/properties/chown.h b/interfaces/kits/js/src/mod_fileio/properties/chown.h index 5ac00ec2fa502fa6f1bb70227a6e28c8f12dcf0b..18dce75e8c19a705a242823b559adc3b441dae53 100644 --- a/interfaces/kits/js/src/mod_fileio/properties/chown.h +++ b/interfaces/kits/js/src/mod_fileio/properties/chown.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -16,7 +16,7 @@ #ifndef INTERFACES_KITS_JS_SRC_MOD_FILEIO_PROPERTIES_CHOWN_H #define INTERFACES_KITS_JS_SRC_MOD_FILEIO_PROPERTIES_CHOWN_H -#include "../../common/napi/n_val.h" +#include "n_val.h" namespace OHOS { namespace DistributedFS { diff --git a/interfaces/kits/js/src/mod_fileio/properties/close.cpp b/interfaces/kits/js/src/mod_fileio/properties/close.cpp index 8024660246bc8babc25fdd2c50123ccd29cd5df7..65b2d230d737e7419b1d5c46fd28fe84046115db 100644 --- a/interfaces/kits/js/src/mod_fileio/properties/close.cpp +++ b/interfaces/kits/js/src/mod_fileio/properties/close.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -19,9 +19,10 @@ #include #include -#include "../../common/napi/n_async/n_async_work_callback.h" -#include "../../common/napi/n_async/n_async_work_promise.h" -#include "../../common/napi/n_func_arg.h" +#include "n_async_work_callback.h" +#include "n_async_work_promise.h" +#include "n_func_arg.h" + namespace OHOS { namespace DistributedFS { namespace ModuleFileIO { diff --git a/interfaces/kits/js/src/mod_fileio/properties/close.h b/interfaces/kits/js/src/mod_fileio/properties/close.h index 6d6a3964682a2e10c6f29306fea72a396b9544a0..4ae95e7fe3d0244e22a26e594e9dc5bf06b619de 100644 --- a/interfaces/kits/js/src/mod_fileio/properties/close.h +++ b/interfaces/kits/js/src/mod_fileio/properties/close.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -16,7 +16,7 @@ #ifndef INTERFACES_KITS_JS_SRC_MOD_FILEIO_PROPERTIES_CLOSE_H #define INTERFACES_KITS_JS_SRC_MOD_FILEIO_PROPERTIES_CLOSE_H -#include "../../common/napi/n_val.h" +#include "n_val.h" namespace OHOS { namespace DistributedFS { diff --git a/interfaces/kits/js/src/mod_fileio/properties/copy_file.cpp b/interfaces/kits/js/src/mod_fileio/properties/copy_file.cpp index 90952c07d39286d071e00b15bba0da0c0ea5f3bb..7205be426a91d540c169ea0a36d656fcaaff6d55 100644 --- a/interfaces/kits/js/src/mod_fileio/properties/copy_file.cpp +++ b/interfaces/kits/js/src/mod_fileio/properties/copy_file.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021-2022 Huawei Device Co., Ltd. + * Copyright (c) 2021-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -17,16 +17,17 @@ #include #include +#include +#include + #include #include #include -#include -#include -#include "../../common/file_helper/fd_guard.h" -#include "../../common/napi/n_async/n_async_work_callback.h" -#include "../../common/napi/n_async/n_async_work_promise.h" -#include "../../common/napi/n_func_arg.h" +#include "file_helper/fd_guard.h" +#include "n_async_work_callback.h" +#include "n_async_work_promise.h" +#include "napi/n_func_arg.h" namespace OHOS { namespace DistributedFS { diff --git a/interfaces/kits/js/src/mod_fileio/properties/copy_file.h b/interfaces/kits/js/src/mod_fileio/properties/copy_file.h index bef01ef1e7a6d0ee54ad37903525210be32e9d98..8b3c6e8e5a1db60d3bf0c9a99d2181129f1aee8d 100644 --- a/interfaces/kits/js/src/mod_fileio/properties/copy_file.h +++ b/interfaces/kits/js/src/mod_fileio/properties/copy_file.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -16,7 +16,7 @@ #ifndef INTERFACES_KITS_JS_SRC_MOD_FILEIO_PROPERTIES_COPY_FILE_H #define INTERFACES_KITS_JS_SRC_MOD_FILEIO_PROPERTIES_COPY_FILE_H -#include "../../common/napi/n_val.h" +#include "n_val.h" namespace OHOS { namespace DistributedFS { diff --git a/interfaces/kits/js/src/mod_fileio/properties/create_stream.cpp b/interfaces/kits/js/src/mod_fileio/properties/create_stream.cpp index 9318aaa2a866f4873c3b85a6e3739fda0e93af3f..018fa88f8a564a88ec0374bf2fb0b99de4152926 100644 --- a/interfaces/kits/js/src/mod_fileio/properties/create_stream.cpp +++ b/interfaces/kits/js/src/mod_fileio/properties/create_stream.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -18,15 +18,14 @@ #include #include -#include "../../common/napi/n_async/n_async_work_callback.h" -#include "../../common/napi/n_async/n_async_work_promise.h" -#include "../../common/napi/n_class.h" -#include "../../common/napi/n_func_arg.h" -#include "../../common/napi/n_val.h" -#include "../../common/uni_error.h" - -#include "../class_stream/stream_entity.h" -#include "../class_stream/stream_n_exporter.h" +#include "class_stream/stream_entity.h" +#include "class_stream/stream_n_exporter.h" +#include "n_async_work_callback.h" +#include "n_async_work_promise.h" +#include "n_class.h" +#include "n_func_arg.h" +#include "n_val.h" +#include "uni_error.h" namespace OHOS { namespace DistributedFS { diff --git a/interfaces/kits/js/src/mod_fileio/properties/create_stream.h b/interfaces/kits/js/src/mod_fileio/properties/create_stream.h index 7c58fa744a9dbb7a0e85d3c7e7258b4695c8c13c..ba73f28ca991001b7c903b3a758ad9fab79e5c8b 100644 --- a/interfaces/kits/js/src/mod_fileio/properties/create_stream.h +++ b/interfaces/kits/js/src/mod_fileio/properties/create_stream.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -16,7 +16,7 @@ #ifndef INTERFACES_KITS_JS_SRC_MOD_FILEIO_PROPERTIES_CREATE_STREAM_H #define INTERFACES_KITS_JS_SRC_MOD_FILEIO_PROPERTIES_CREATE_STREAM_H -#include "../../common/napi/uni_header.h" +#include "uni_header.h" namespace OHOS { namespace DistributedFS { diff --git a/interfaces/kits/js/src/mod_fileio/properties/fchmod.cpp b/interfaces/kits/js/src/mod_fileio/properties/fchmod.cpp index 97f75b336aece34e9c60b8aa4145a03d5f8c50a1..8f69c921c7a4d532109bfafe00af73f684a4b3ac 100644 --- a/interfaces/kits/js/src/mod_fileio/properties/fchmod.cpp +++ b/interfaces/kits/js/src/mod_fileio/properties/fchmod.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -16,13 +16,15 @@ #include "fchmod.h" #include #include -#include #include #include -#include "../../common/napi/n_async/n_async_work_callback.h" -#include "../../common/napi/n_async/n_async_work_promise.h" -#include "../../common/napi/n_func_arg.h" +#include + +#include "n_async_work_callback.h" +#include "n_async_work_promise.h" +#include "n_func_arg.h" + namespace OHOS { namespace DistributedFS { namespace ModuleFileIO { diff --git a/interfaces/kits/js/src/mod_fileio/properties/fchmod.h b/interfaces/kits/js/src/mod_fileio/properties/fchmod.h index eb7711822870984742d1190bedfb61200768b2d6..3628298d582db73e4e618977b9a2a0cd1c31027e 100644 --- a/interfaces/kits/js/src/mod_fileio/properties/fchmod.h +++ b/interfaces/kits/js/src/mod_fileio/properties/fchmod.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -16,7 +16,7 @@ #ifndef INTERFACES_KITS_JS_SRC_MOD_FILEIO_PROPERTIES_FCHMOD_H #define INTERFACES_KITS_JS_SRC_MOD_FILEIO_PROPERTIES_FCHMOD_H -#include "../../common/napi/n_val.h" +#include "n_val.h" namespace OHOS { namespace DistributedFS { diff --git a/interfaces/kits/js/src/mod_fileio/properties/fchown.cpp b/interfaces/kits/js/src/mod_fileio/properties/fchown.cpp index 0d5f00ad68f4ffa9ecb154921e656994b8c7a92f..4c35eef74df46acfa56d40b9bd8c578cb774d282 100644 --- a/interfaces/kits/js/src/mod_fileio/properties/fchown.cpp +++ b/interfaces/kits/js/src/mod_fileio/properties/fchown.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -19,9 +19,10 @@ #include #include -#include "../../common/napi/n_async/n_async_work_callback.h" -#include "../../common/napi/n_async/n_async_work_promise.h" -#include "../../common/napi/n_func_arg.h" +#include "n_async_work_callback.h" +#include "n_async_work_promise.h" +#include "n_func_arg.h" + namespace OHOS { namespace DistributedFS { namespace ModuleFileIO { diff --git a/interfaces/kits/js/src/mod_fileio/properties/fchown.h b/interfaces/kits/js/src/mod_fileio/properties/fchown.h index 7439f2e542f346eeb6f8c9affaca8f3a8705e752..221d93dd022ff9890e84a7c81067513598d75b29 100644 --- a/interfaces/kits/js/src/mod_fileio/properties/fchown.h +++ b/interfaces/kits/js/src/mod_fileio/properties/fchown.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -16,7 +16,7 @@ #ifndef INTERFACES_KITS_JS_SRC_MOD_FILEIO_PROPERTIES_FCHOWN_H #define INTERFACES_KITS_JS_SRC_MOD_FILEIO_PROPERTIES_FCHOWN_H -#include "../../common/napi/n_val.h" +#include "n_val.h" namespace OHOS { namespace DistributedFS { diff --git a/interfaces/kits/js/src/mod_fileio/properties/fdatasync.cpp b/interfaces/kits/js/src/mod_fileio/properties/fdatasync.cpp index 6ed9509800b4ee1e8b7fb3a6983ac2db63a090a1..31f51ef49ccaa57282557a0115a242140980136a 100644 --- a/interfaces/kits/js/src/mod_fileio/properties/fdatasync.cpp +++ b/interfaces/kits/js/src/mod_fileio/properties/fdatasync.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -14,15 +14,18 @@ */ #include "fdatasync.h" + #include #include -#include #include #include -#include "../../common/napi/n_async/n_async_work_callback.h" -#include "../../common/napi/n_async/n_async_work_promise.h" -#include "../../common/napi/n_func_arg.h" +#include + +#include "n_async_work_callback.h" +#include "n_async_work_promise.h" +#include "n_func_arg.h" + namespace OHOS { namespace DistributedFS { namespace ModuleFileIO { diff --git a/interfaces/kits/js/src/mod_fileio/properties/fdatasync.h b/interfaces/kits/js/src/mod_fileio/properties/fdatasync.h index f10fcbde3a1faa694680ef8ce97aaba17824e65f..3eb4f1391a857dc369a6865f0602a1c9af56c03d 100644 --- a/interfaces/kits/js/src/mod_fileio/properties/fdatasync.h +++ b/interfaces/kits/js/src/mod_fileio/properties/fdatasync.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -16,7 +16,7 @@ #ifndef INTERFACES_KITS_JS_SRC_MOD_FILEIO_PROPERTIES_FDATASYNC_H #define INTERFACES_KITS_JS_SRC_MOD_FILEIO_PROPERTIES_FDATASYNC_H -#include "../../common/napi/n_val.h" +#include "n_val.h" namespace OHOS { namespace DistributedFS { diff --git a/interfaces/kits/js/src/mod_fileio/properties/fdopen_stream.cpp b/interfaces/kits/js/src/mod_fileio/properties/fdopen_stream.cpp index 3cb25ab5cc420a436d1c05f2b49a9bd32bcd9327..010924e09e68ca10bf3128b5dc3cab0cc7ed1c8e 100644 --- a/interfaces/kits/js/src/mod_fileio/properties/fdopen_stream.cpp +++ b/interfaces/kits/js/src/mod_fileio/properties/fdopen_stream.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -14,17 +14,18 @@ */ #include "fdopen_stream.h" + #include #include -#include "../../common/napi/n_async/n_async_work_callback.h" -#include "../../common/napi/n_async/n_async_work_promise.h" -#include "../../common/napi/n_class.h" -#include "../../common/napi/n_func_arg.h" -#include "../../common/napi/n_val.h" -#include "../../common/uni_error.h" -#include "../class_stream/stream_entity.h" -#include "../class_stream/stream_n_exporter.h" +#include "class_stream/stream_entity.h" +#include "class_stream/stream_n_exporter.h" +#include "n_async_work_callback.h" +#include "n_async_work_promise.h" +#include "n_class.h" +#include "n_func_arg.h" +#include "n_val.h" +#include "uni_error.h" namespace OHOS { namespace DistributedFS { diff --git a/interfaces/kits/js/src/mod_fileio/properties/fdopen_stream.h b/interfaces/kits/js/src/mod_fileio/properties/fdopen_stream.h index 195369eceec8a73a7278380675ae64be6a358626..b449254b41a96710ef1b1ef042de442322de6849 100644 --- a/interfaces/kits/js/src/mod_fileio/properties/fdopen_stream.h +++ b/interfaces/kits/js/src/mod_fileio/properties/fdopen_stream.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -16,7 +16,7 @@ #ifndef INTERFACES_KITS_JS_SRC_MOD_FILEIO_PROPERTIES_FDOPEN_STREAM_H #define INTERFACES_KITS_JS_SRC_MOD_FILEIO_PROPERTIES_FDOPEN_STREAM_H -#include "../../common/napi/uni_header.h" +#include "uni_header.h" namespace OHOS { namespace DistributedFS { diff --git a/interfaces/kits/js/src/mod_fileio/properties/fstat.cpp b/interfaces/kits/js/src/mod_fileio/properties/fstat.cpp index a6dfddc44d7d411823cee9b82da406a961db1ed3..5ba9c805849526f651e559aa3ba2ec813607b703 100644 --- a/interfaces/kits/js/src/mod_fileio/properties/fstat.cpp +++ b/interfaces/kits/js/src/mod_fileio/properties/fstat.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -17,15 +17,14 @@ #include #include -#include "../../common/napi/n_async/n_async_work_callback.h" -#include "../../common/napi/n_async/n_async_work_promise.h" -#include "../../common/napi/n_class.h" -#include "../../common/napi/n_func_arg.h" -#include "../../common/napi/n_val.h" -#include "../../common/uni_error.h" - -#include "../class_stat/stat_entity.h" -#include "../class_stat/stat_n_exporter.h" +#include "class_stat/stat_entity.h" +#include "class_stat/stat_n_exporter.h" +#include "n_async_work_callback.h" +#include "n_async_work_promise.h" +#include "n_class.h" +#include "n_func_arg.h" +#include "n_val.h" +#include "uni_error.h" namespace OHOS { namespace DistributedFS { diff --git a/interfaces/kits/js/src/mod_fileio/properties/fstat.h b/interfaces/kits/js/src/mod_fileio/properties/fstat.h index 27395df81e9d5802c873d5c7be42b066fc254640..d05acf0b4d92ad540d5356d43fe9915001100f6f 100644 --- a/interfaces/kits/js/src/mod_fileio/properties/fstat.h +++ b/interfaces/kits/js/src/mod_fileio/properties/fstat.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -16,7 +16,7 @@ #ifndef INTERFACES_KITS_JS_SRC_MOD_FILEIO_PROPERTIES_FSTAT_H #define INTERFACES_KITS_JS_SRC_MOD_FILEIO_PROPERTIES_FSTAT_H -#include "../../common/napi/uni_header.h" +#include "uni_header.h" namespace OHOS { namespace DistributedFS { diff --git a/interfaces/kits/js/src/mod_fileio/properties/fsync.cpp b/interfaces/kits/js/src/mod_fileio/properties/fsync.cpp index 1e0d27f10547b01b2ab978286d039fdd233ae5ab..f4761b1f3e482927812d222e7f1dab68d31478b8 100644 --- a/interfaces/kits/js/src/mod_fileio/properties/fsync.cpp +++ b/interfaces/kits/js/src/mod_fileio/properties/fsync.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -19,9 +19,9 @@ #include #include -#include "../../common/napi/n_async/n_async_work_callback.h" -#include "../../common/napi/n_async/n_async_work_promise.h" -#include "../../common/napi/n_func_arg.h" +#include "n_async_work_callback.h" +#include "n_async_work_promise.h" +#include "n_func_arg.h" namespace OHOS { namespace DistributedFS { diff --git a/interfaces/kits/js/src/mod_fileio/properties/fsync.h b/interfaces/kits/js/src/mod_fileio/properties/fsync.h index 0e2a54e040fd05388608de6d0bc3a38ad264c868..7459dccb81a63a36b17ec09b2b6572fb91eb1fad 100644 --- a/interfaces/kits/js/src/mod_fileio/properties/fsync.h +++ b/interfaces/kits/js/src/mod_fileio/properties/fsync.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -16,7 +16,7 @@ #ifndef INTERFACES_KITS_JS_SRC_MOD_FILEIO_PROPERTIES_FSYNC_H #define INTERFACES_KITS_JS_SRC_MOD_FILEIO_PROPERTIES_FSYNC_H -#include "../../common/napi/n_val.h" +#include "n_val.h" namespace OHOS { namespace DistributedFS { diff --git a/interfaces/kits/js/src/mod_fileio/properties/ftruncate.cpp b/interfaces/kits/js/src/mod_fileio/properties/ftruncate.cpp index ed0fb67fe07daf37ab551593fac9aeee9e6a3389..26ba27492913ea91e794e557f453bf71addb5ea4 100644 --- a/interfaces/kits/js/src/mod_fileio/properties/ftruncate.cpp +++ b/interfaces/kits/js/src/mod_fileio/properties/ftruncate.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -19,9 +19,9 @@ #include #include -#include "../../common/napi/n_async/n_async_work_callback.h" -#include "../../common/napi/n_async/n_async_work_promise.h" -#include "../../common/napi/n_func_arg.h" +#include "n_async_work_callback.h" +#include "n_async_work_promise.h" +#include "n_func_arg.h" namespace OHOS { namespace DistributedFS { diff --git a/interfaces/kits/js/src/mod_fileio/properties/ftruncate.h b/interfaces/kits/js/src/mod_fileio/properties/ftruncate.h index f9d076efc337ce69f6ea7d804d07a580964b1c91..0b03edbee9cd0e0d73e4ca6af1df290f0acf552a 100644 --- a/interfaces/kits/js/src/mod_fileio/properties/ftruncate.h +++ b/interfaces/kits/js/src/mod_fileio/properties/ftruncate.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -16,7 +16,7 @@ #ifndef INTERFACES_KITS_JS_SRC_MOD_FILEIO_PROPERTIES_FTRUNCATE_H #define INTERFACES_KITS_JS_SRC_MOD_FILEIO_PROPERTIES_FTRUNCATE_H -#include "../../common/napi/n_val.h" +#include "n_val.h" namespace OHOS { namespace DistributedFS { diff --git a/interfaces/kits/js/src/mod_fileio/properties/hash.cpp b/interfaces/kits/js/src/mod_fileio/properties/hash.cpp index 57af090dd00aa475febb7c7f4d30f2c808472fbe..935787abf088e8d3f95ca82235b6c29cc1a12032 100644 --- a/interfaces/kits/js/src/mod_fileio/properties/hash.cpp +++ b/interfaces/kits/js/src/mod_fileio/properties/hash.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -19,7 +19,7 @@ #include #include -#include "../../common/file_helper/hash_file.h" +#include "file_helper/hash_file.h" namespace OHOS { namespace DistributedFS { diff --git a/interfaces/kits/js/src/mod_fileio/properties/hash.h b/interfaces/kits/js/src/mod_fileio/properties/hash.h index 8aca34ce1315691044ee8e86d9605a104a8c07d1..afd3de858016b443496caf31062820653155a780 100644 --- a/interfaces/kits/js/src/mod_fileio/properties/hash.h +++ b/interfaces/kits/js/src/mod_fileio/properties/hash.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -16,10 +16,10 @@ #ifndef INTERFACES_KITS_JS_SRC_MOD_FILEIO_PROPERTIES_HASH_H #define INTERFACES_KITS_JS_SRC_MOD_FILEIO_PROPERTIES_HASH_H -#include "../../common/log.h" -#include "../../common/napi/n_async/n_async_work_callback.h" -#include "../../common/napi/n_async/n_async_work_promise.h" -#include "../../common/napi/n_func_arg.h" +#include "log.h" +#include "n_async_work_callback.h" +#include "n_async_work_promise.h" +#include "n_func_arg.h" namespace OHOS { namespace DistributedFS { diff --git a/interfaces/kits/js/src/mod_fileio/properties/lchown.cpp b/interfaces/kits/js/src/mod_fileio/properties/lchown.cpp index 24e44fd9c8a4e3d777c7e95f43a6e9b56f77f189..9009dfecea25b8d66e8c17e702935ebea72f04a0 100644 --- a/interfaces/kits/js/src/mod_fileio/properties/lchown.cpp +++ b/interfaces/kits/js/src/mod_fileio/properties/lchown.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -19,9 +19,10 @@ #include #include -#include "../../common/napi/n_async/n_async_work_callback.h" -#include "../../common/napi/n_async/n_async_work_promise.h" -#include "../../common/napi/n_func_arg.h" +#include "n_async_work_callback.h" +#include "n_async_work_promise.h" +#include "n_func_arg.h" + namespace OHOS { namespace DistributedFS { namespace ModuleFileIO { diff --git a/interfaces/kits/js/src/mod_fileio/properties/lchown.h b/interfaces/kits/js/src/mod_fileio/properties/lchown.h index c13ad09673d250a4185c7b6ca36cbb0fef0896be..7d5ecb8541b74ddd353a036e443d5ebc34a9ce89 100644 --- a/interfaces/kits/js/src/mod_fileio/properties/lchown.h +++ b/interfaces/kits/js/src/mod_fileio/properties/lchown.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -16,7 +16,7 @@ #ifndef INTERFACES_KITS_JS_SRC_MOD_FILEIO_PROPERTIES_LCHOWN_H #define INTERFACES_KITS_JS_SRC_MOD_FILEIO_PROPERTIES_LCHOWN_H -#include "../../common/napi/n_val.h" +#include "n_val.h" namespace OHOS { namespace DistributedFS { diff --git a/interfaces/kits/js/src/mod_fileio/properties/link.cpp b/interfaces/kits/js/src/mod_fileio/properties/link.cpp index a6d18a42f3f319951839a0268b4e95f611442250..ce0560d1a5b8faf23cbecd789a67d0a44017717d 100644 --- a/interfaces/kits/js/src/mod_fileio/properties/link.cpp +++ b/interfaces/kits/js/src/mod_fileio/properties/link.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -19,9 +19,9 @@ #include #include -#include "../../common/napi/n_async/n_async_work_callback.h" -#include "../../common/napi/n_async/n_async_work_promise.h" -#include "../../common/napi/n_func_arg.h" +#include "n_async_work_callback.h" +#include "n_async_work_promise.h" +#include "n_func_arg.h" namespace OHOS { namespace DistributedFS { diff --git a/interfaces/kits/js/src/mod_fileio/properties/link.h b/interfaces/kits/js/src/mod_fileio/properties/link.h index f287a24e75023561a4227eab08be337b337ded7e..184715cee30a823637732df6f8cba0c596b8f9e8 100644 --- a/interfaces/kits/js/src/mod_fileio/properties/link.h +++ b/interfaces/kits/js/src/mod_fileio/properties/link.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -16,7 +16,7 @@ #ifndef INTERFACES_KITS_JS_SRC_MOD_FILEIO_PROPERTIES_LINK_H #define INTERFACES_KITS_JS_SRC_MOD_FILEIO_PROPERTIES_LINK_H -#include "../../common/napi/n_val.h" +#include "n_val.h" namespace OHOS { namespace DistributedFS { diff --git a/interfaces/kits/js/src/mod_fileio/properties/lseek.cpp b/interfaces/kits/js/src/mod_fileio/properties/lseek.cpp index 11ecc64b4a77618348d2ddf686e030b6e6a448b2..bbc523633e6e3d0a7a8ed0d255cb89e574fa1922 100644 --- a/interfaces/kits/js/src/mod_fileio/properties/lseek.cpp +++ b/interfaces/kits/js/src/mod_fileio/properties/lseek.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -13,13 +13,15 @@ * limitations under the License. */ #include "lseek.h" + #include #include #include -#include "../../common/napi/n_async/n_async_work_callback.h" -#include "../../common/napi/n_async/n_async_work_promise.h" -#include "../../common/napi/n_func_arg.h" +#include "n_async_work_callback.h" +#include "n_async_work_promise.h" +#include "n_func_arg.h" + namespace OHOS { namespace DistributedFS { namespace ModuleFileIO { diff --git a/interfaces/kits/js/src/mod_fileio/properties/lseek.h b/interfaces/kits/js/src/mod_fileio/properties/lseek.h index b8ffb861cb7b6daa8193e42dd1fee4d659c1d018..7e7675241d038af035b2494603d949c8e7ca7a0d 100644 --- a/interfaces/kits/js/src/mod_fileio/properties/lseek.h +++ b/interfaces/kits/js/src/mod_fileio/properties/lseek.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -16,7 +16,7 @@ #ifndef INTERFACES_KITS_JS_SRC_MOD_FILEIO_PROPERTIES_LSEEK_H #define INTERFACES_KITS_JS_SRC_MOD_FILEIO_PROPERTIES_LSEEK_H -#include "../../common/napi/n_val.h" +#include "n_val.h" namespace OHOS { namespace DistributedFS { diff --git a/interfaces/kits/js/src/mod_fileio/properties/lstat.cpp b/interfaces/kits/js/src/mod_fileio/properties/lstat.cpp index f6e511309d96b3cec718f988509e88637d028ddf..b447d9b62cb9588744488b91c5f6894fe8233bdb 100644 --- a/interfaces/kits/js/src/mod_fileio/properties/lstat.cpp +++ b/interfaces/kits/js/src/mod_fileio/properties/lstat.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -17,15 +17,14 @@ #include #include -#include "../../common/napi/n_async/n_async_work_callback.h" -#include "../../common/napi/n_async/n_async_work_promise.h" -#include "../../common/napi/n_class.h" -#include "../../common/napi/n_func_arg.h" -#include "../../common/napi/n_val.h" -#include "../../common/uni_error.h" - -#include "../class_stat/stat_entity.h" -#include "../class_stat/stat_n_exporter.h" +#include "class_stat/stat_entity.h" +#include "class_stat/stat_n_exporter.h" +#include "n_async_work_callback.h" +#include "n_async_work_promise.h" +#include "n_class.h" +#include "n_func_arg.h" +#include "n_val.h" +#include "uni_error.h" namespace OHOS { namespace DistributedFS { diff --git a/interfaces/kits/js/src/mod_fileio/properties/lstat.h b/interfaces/kits/js/src/mod_fileio/properties/lstat.h index 6bd24beff996b5bfc26c1caec660f5c57cd8e242..9516722f1b7133b852aecbd67d5326ceaec6c2a1 100644 --- a/interfaces/kits/js/src/mod_fileio/properties/lstat.h +++ b/interfaces/kits/js/src/mod_fileio/properties/lstat.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -16,7 +16,7 @@ #ifndef INTERFACES_KITS_JS_SRC_MOD_FILEIO_PROPERTIES_LSTAT_H #define INTERFACES_KITS_JS_SRC_MOD_FILEIO_PROPERTIES_LSTAT_H -#include "../../common/napi/uni_header.h" +#include "uni_header.h" namespace OHOS { namespace DistributedFS { diff --git a/interfaces/kits/js/src/mod_fileio/properties/mkdtemp.cpp b/interfaces/kits/js/src/mod_fileio/properties/mkdtemp.cpp index 93c10eeb0c3a7f06d53ae8d8210c45734b8a5906..297320b7cec041aca729df02e47b558c3be4c276 100644 --- a/interfaces/kits/js/src/mod_fileio/properties/mkdtemp.cpp +++ b/interfaces/kits/js/src/mod_fileio/properties/mkdtemp.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021-2022 Huawei Device Co., Ltd. + * Copyright (c) 2021-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -15,9 +15,10 @@ #include "mkdtemp.h" -#include "../../common/napi/n_async/n_async_work_callback.h" -#include "../../common/napi/n_async/n_async_work_promise.h" -#include "../../common/napi/n_func_arg.h" +#include "n_async_work_callback.h" +#include "n_async_work_promise.h" +#include "n_func_arg.h" + namespace OHOS { namespace DistributedFS { namespace ModuleFileIO { diff --git a/interfaces/kits/js/src/mod_fileio/properties/mkdtemp.h b/interfaces/kits/js/src/mod_fileio/properties/mkdtemp.h index de9a7aed1df9d29d2737ea623ce7059ce388a93d..11c89480794cd152a063a8816e5fc1038c096335 100644 --- a/interfaces/kits/js/src/mod_fileio/properties/mkdtemp.h +++ b/interfaces/kits/js/src/mod_fileio/properties/mkdtemp.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -16,7 +16,7 @@ #ifndef INTERFACES_KITS_JS_SRC_MOD_FILEIO_PROPERTIES_MKDTEMP_H #define INTERFACES_KITS_JS_SRC_MOD_FILEIO_PROPERTIES_MKDTEMP_H -#include "../../common/napi/n_val.h" +#include "n_val.h" namespace OHOS { namespace DistributedFS { diff --git a/interfaces/kits/js/src/mod_fileio/properties/open.cpp b/interfaces/kits/js/src/mod_fileio/properties/open.cpp index 9ef34c2c01ca3687f6d60b132d67cf788afeee1c..2bc4be8c31906af9d070ebce3b07d4a5da9d8ce9 100644 --- a/interfaces/kits/js/src/mod_fileio/properties/open.cpp +++ b/interfaces/kits/js/src/mod_fileio/properties/open.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -14,16 +14,17 @@ */ #include "open.h" + #include #include #include #include -#include "remote_uri.h" -#include "../../common/napi/n_async/n_async_work_callback.h" -#include "../../common/napi/n_async/n_async_work_promise.h" -#include "../../common/napi/n_func_arg.h" -#include "../common_func.h" +#include "common_func.h" +#include "n_async/n_async_work_callback.h" +#include "n_async/n_async_work_promise.h" +#include "n_func_arg.h" +#include "remote_uri.h" namespace OHOS { namespace DistributedFS { diff --git a/interfaces/kits/js/src/mod_fileio/properties/open.h b/interfaces/kits/js/src/mod_fileio/properties/open.h index f6b6d718cb0f58c91b30071ac11a87459fc8f765..954d790cdacc8023346ea632aa80753449cb3519 100644 --- a/interfaces/kits/js/src/mod_fileio/properties/open.h +++ b/interfaces/kits/js/src/mod_fileio/properties/open.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -16,7 +16,7 @@ #ifndef INTERFACES_KITS_JS_SRC_MOD_FILEIO_PROPERTIES_OPEN_H #define INTERFACES_KITS_JS_SRC_MOD_FILEIO_PROPERTIES_OPEN_H -#include "../../common/napi/n_val.h" +#include "n_val.h" namespace OHOS { namespace DistributedFS { diff --git a/interfaces/kits/js/src/mod_fileio/properties/open_dir.cpp b/interfaces/kits/js/src/mod_fileio/properties/open_dir.cpp index d46d8b41b3a5444785c6d007d0899269133ede70..c6d04b10090ee88484c4f781ca16b15f12a3593b 100644 --- a/interfaces/kits/js/src/mod_fileio/properties/open_dir.cpp +++ b/interfaces/kits/js/src/mod_fileio/properties/open_dir.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021-2022 Huawei Device Co., Ltd. + * Copyright (c) 2021-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -14,18 +14,19 @@ */ #include "open_dir.h" + #include #include #include -#include "../../common/napi/n_async/n_async_work_callback.h" -#include "../../common/napi/n_async/n_async_work_promise.h" -#include "../../common/napi/n_class.h" -#include "../../common/napi/n_func_arg.h" -#include "../../common/napi/n_val.h" -#include "../../common/uni_error.h" -#include "../class_dir/dir_entity.h" -#include "../class_dir/dir_n_exporter.h" +#include "class_dir/dir_entity.h" +#include "class_dir/dir_n_exporter.h" +#include "n_async_work_callback.h" +#include "n_async_work_promise.h" +#include "n_class.h" +#include "n_func_arg.h" +#include "n_val.h" +#include "uni_error.h" namespace OHOS { namespace DistributedFS { diff --git a/interfaces/kits/js/src/mod_fileio/properties/open_dir.h b/interfaces/kits/js/src/mod_fileio/properties/open_dir.h index e2e07d3b068ca8b5f40d7c98b0eef91a0abcf57d..55429834d2e6c0a53fa9c1de34303de2cd8b180d 100644 --- a/interfaces/kits/js/src/mod_fileio/properties/open_dir.h +++ b/interfaces/kits/js/src/mod_fileio/properties/open_dir.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -16,7 +16,7 @@ #ifndef INTERFACES_KITS_JS_SRC_MOD_FILEIO_PROPERTIES_OPEN_DIR_H #define INTERFACES_KITS_JS_SRC_MOD_FILEIO_PROPERTIES_OPEN_DIR_H -#include "../../common/napi/uni_header.h" +#include "uni_header.h" namespace OHOS { namespace DistributedFS { diff --git a/interfaces/kits/js/src/mod_fileio/properties/open_v9.h b/interfaces/kits/js/src/mod_fileio/properties/open_v9.h index ac8921b4cbcbe588332b93fdfe20f3ce55c498a4..2c61283c58da5a817007b21ac46ae87a335b32f4 100644 --- a/interfaces/kits/js/src/mod_fileio/properties/open_v9.h +++ b/interfaces/kits/js/src/mod_fileio/properties/open_v9.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 Huawei Device Co., Ltd. + * Copyright (c) 2022-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -17,7 +17,7 @@ #define INTERFACES_KITS_JS_SRC_MOD_FILEIO_PROPERTIES_OPEN_V9_H #include "iremote_broker.h" -#include "../../common/napi/uni_header.h" +#include "uni_header.h" namespace OHOS { namespace DistributedFS { diff --git a/interfaces/kits/js/src/mod_fileio/properties/posix_fallocate.cpp b/interfaces/kits/js/src/mod_fileio/properties/posix_fallocate.cpp index fe9694d36c184b224afee82d73bef29cb7c921c5..c9150bbdb35a173203cbde9e72c4c1508e709430 100644 --- a/interfaces/kits/js/src/mod_fileio/properties/posix_fallocate.cpp +++ b/interfaces/kits/js/src/mod_fileio/properties/posix_fallocate.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021-2022 Huawei Device Co., Ltd. + * Copyright (c) 2021-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -13,14 +13,15 @@ * limitations under the License. */ #include "posix_fallocate.h" + #include #include #include #include -#include "../../common/napi/n_async/n_async_work_callback.h" -#include "../../common/napi/n_async/n_async_work_promise.h" -#include "../../common/napi/n_func_arg.h" +#include "n_async_work_callback.h" +#include "n_async_work_promise.h" +#include "n_func_arg.h" namespace OHOS { namespace DistributedFS { diff --git a/interfaces/kits/js/src/mod_fileio/properties/posix_fallocate.h b/interfaces/kits/js/src/mod_fileio/properties/posix_fallocate.h index c26c70465bb28497c41c39f884f78d85f40f4bcf..4522b78fc41a0c0c57c928922df36d6e1398bb57 100644 --- a/interfaces/kits/js/src/mod_fileio/properties/posix_fallocate.h +++ b/interfaces/kits/js/src/mod_fileio/properties/posix_fallocate.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -16,7 +16,7 @@ #ifndef INTERFACES_KITS_JS_SRC_MOD_FILEIO_PROPERTIES_POSIX_FALLOCATE_H #define INTERFACES_KITS_JS_SRC_MOD_FILEIO_PROPERTIES_POSIX_FALLOCATE_H -#include "../../common/napi/n_val.h" +#include "n_val.h" namespace OHOS { namespace DistributedFS { diff --git a/interfaces/kits/js/src/mod_fileio/properties/prop_n_exporter.cpp b/interfaces/kits/js/src/mod_fileio/properties/prop_n_exporter.cpp index 05567297f274ef23026e6e187573b1930d905d6e..b62f235a3b16f3c924bc7c350fb810ece49b1c64 100644 --- a/interfaces/kits/js/src/mod_fileio/properties/prop_n_exporter.cpp +++ b/interfaces/kits/js/src/mod_fileio/properties/prop_n_exporter.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021-2022 Huawei Device Co., Ltd. + * Copyright (c) 2021-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -21,10 +21,10 @@ #include #include -#include "../common_func.h" #include "chmod.h" #include "chown.h" #include "close.h" +#include "common_func.h" #include "copy_file.h" #include "create_stream.h" #include "fchmod.h" @@ -40,8 +40,8 @@ #include "lseek.h" #include "lstat.h" #include "mkdtemp.h" -#include "open.h" #include "open_dir.h" +#include "open.h" #include "posix_fallocate.h" #include "read_dir.h" #include "read_text.h" diff --git a/interfaces/kits/js/src/mod_fileio/properties/prop_n_exporter.h b/interfaces/kits/js/src/mod_fileio/properties/prop_n_exporter.h index 107a12381d27c5180ae9930330ebb5acd0f77b5c..f5061d7a8b41cbf716cd9c4992e3266bb3f2f420 100644 --- a/interfaces/kits/js/src/mod_fileio/properties/prop_n_exporter.h +++ b/interfaces/kits/js/src/mod_fileio/properties/prop_n_exporter.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -16,10 +16,10 @@ #ifndef INTERFACES_KITS_JS_SRC_MOD_FILEIO_PROPERTIES_PROP_N_EXPORTER_H #define INTERFACES_KITS_JS_SRC_MOD_FILEIO_PROPERTIES_PROP_N_EXPORTER_H -#include "../../common/napi/n_async/n_ref.h" -#include "../../common/napi/n_exporter.h" -#include "../../common/napi/n_val.h" -#include "../../common/uni_error.h" +#include "n_async/n_ref.h" +#include "n_exporter.h" +#include "n_val.h" +#include "uni_error.h" namespace OHOS { namespace DistributedFS { diff --git a/interfaces/kits/js/src/mod_fileio/properties/read_dir.cpp b/interfaces/kits/js/src/mod_fileio/properties/read_dir.cpp index 6a3164701828ddb1dbde73a7aa09210d8882daf7..470a03e18390d5a084977b7d9b324a7ed44f190b 100644 --- a/interfaces/kits/js/src/mod_fileio/properties/read_dir.cpp +++ b/interfaces/kits/js/src/mod_fileio/properties/read_dir.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 Huawei Device Co., Ltd. + * Copyright (c) 2022-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -20,12 +20,12 @@ #include #include -#include "../../common/napi/n_async/n_async_work_callback.h" -#include "../../common/napi/n_async/n_async_work_promise.h" -#include "../../common/napi/n_class.h" -#include "../../common/napi/n_func_arg.h" -#include "../../common/napi/n_val.h" -#include "../../common/uni_error.h" +#include "n_async_work_callback.h" +#include "n_async_work_promise.h" +#include "n_class.h" +#include "n_func_arg.h" +#include "n_val.h" +#include "uni_error.h" namespace OHOS { namespace DistributedFS { diff --git a/interfaces/kits/js/src/mod_fileio/properties/read_dir.h b/interfaces/kits/js/src/mod_fileio/properties/read_dir.h index e08fdcbfddbdb82b8117879ec2eb5ef6cd56c828..7fe0b4d38e9e13fa98270d6dd9354f896a164872 100644 --- a/interfaces/kits/js/src/mod_fileio/properties/read_dir.h +++ b/interfaces/kits/js/src/mod_fileio/properties/read_dir.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 Huawei Device Co., Ltd. + * Copyright (c) 2022-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -16,7 +16,7 @@ #ifndef INTERFACES_KITS_JS_SRC_MOD_FILEIO_PROPERTIES_READ_DIR_H #define INTERFACES_KITS_JS_SRC_MOD_FILEIO_PROPERTIES_READ_DIR_H -#include "../../common/napi/uni_header.h" +#include "uni_header.h" namespace OHOS { namespace DistributedFS { diff --git a/interfaces/kits/js/src/mod_fileio/properties/read_text.cpp b/interfaces/kits/js/src/mod_fileio/properties/read_text.cpp index 4a2b909b6347161a40a5289a0af89aa1425db22c..181f4c17fdaae4c05e6f28aaaf7ad3dbfdbf992d 100644 --- a/interfaces/kits/js/src/mod_fileio/properties/read_text.cpp +++ b/interfaces/kits/js/src/mod_fileio/properties/read_text.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021-2022 Huawei Device Co., Ltd. + * Copyright (c) 2021-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -16,14 +16,16 @@ #include #include -#include #include #include -#include "../../common/file_helper/fd_guard.h" -#include "../../common/napi/n_async/n_async_work_callback.h" -#include "../../common/napi/n_async/n_async_work_promise.h" -#include "../../common/napi/n_func_arg.h" -#include "../common_func.h" + +#include + +#include "common_func.h" +#include "file_helper/fd_guard.h" +#include "n_async_work_callback.h" +#include "n_async_work_promise.h" +#include "n_func_arg.h" namespace OHOS { namespace DistributedFS { diff --git a/interfaces/kits/js/src/mod_fileio/properties/read_text.h b/interfaces/kits/js/src/mod_fileio/properties/read_text.h index b56fc7efc1139705bfa4e93bda4cc1c2d3b92c6f..6c2c5426a88eb6fc274ec8d1a97efad773de1cf3 100644 --- a/interfaces/kits/js/src/mod_fileio/properties/read_text.h +++ b/interfaces/kits/js/src/mod_fileio/properties/read_text.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -16,9 +16,9 @@ #ifndef INTERFACES_KITS_JS_SRC_MOD_FILEIO_PROPERTIES_READ_TEXT_H #define INTERFACES_KITS_JS_SRC_MOD_FILEIO_PROPERTIES_READ_TEXT_H -#include "../../common/napi/n_async/n_ref.h" -#include "../../common/napi/n_val.h" -#include "../../common/uni_error.h" +#include "n_ref.h" +#include "n_val.h" +#include "uni_error.h" namespace OHOS { namespace DistributedFS { diff --git a/interfaces/kits/js/src/mod_fileio/properties/rename.cpp b/interfaces/kits/js/src/mod_fileio/properties/rename.cpp index 5d81388bc9933149f513a8ba943f12f174c3d516..6633291485e4128fa77fc2a90016a5d25a5b23cc 100644 --- a/interfaces/kits/js/src/mod_fileio/properties/rename.cpp +++ b/interfaces/kits/js/src/mod_fileio/properties/rename.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -19,9 +19,9 @@ #include #include -#include "../../common/napi/n_async/n_async_work_callback.h" -#include "../../common/napi/n_async/n_async_work_promise.h" -#include "../../common/napi/n_func_arg.h" +#include "n_async_work_callback.h" +#include "n_async_work_promise.h" +#include "n_func_arg.h" namespace OHOS { namespace DistributedFS { diff --git a/interfaces/kits/js/src/mod_fileio/properties/rename.h b/interfaces/kits/js/src/mod_fileio/properties/rename.h index 0333170a66be1f5666ae5f17de6856d0bbf4e81c..47295d6cf7859ea8e965bea218a517802754751c 100644 --- a/interfaces/kits/js/src/mod_fileio/properties/rename.h +++ b/interfaces/kits/js/src/mod_fileio/properties/rename.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -16,7 +16,8 @@ #ifndef INTERFACES_KITS_JS_SRC_MOD_FILEIO_PROPERTIES_RENAME_H #define INTERFACES_KITS_JS_SRC_MOD_FILEIO_PROPERTIES_RENAME_H -#include "../../common/napi/n_val.h" +#include "n_val.h" + namespace OHOS { namespace DistributedFS { namespace ModuleFileIO { diff --git a/interfaces/kits/js/src/mod_fileio/properties/rmdir.cpp b/interfaces/kits/js/src/mod_fileio/properties/rmdir.cpp index 46111a91ba0d7446fd078a361ca24c680941020c..df7e93517855f283703ebacca417bdf53b539adf 100644 --- a/interfaces/kits/js/src/mod_fileio/properties/rmdir.cpp +++ b/interfaces/kits/js/src/mod_fileio/properties/rmdir.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -18,9 +18,11 @@ #include #include #include -#include "../../common/napi/n_async/n_async_work_callback.h" -#include "../../common/napi/n_async/n_async_work_promise.h" -#include "../../common/napi/n_func_arg.h" + +#include "n_async_work_callback.h" +#include "n_async_work_promise.h" +#include "n_func_arg.h" + namespace OHOS { namespace DistributedFS { namespace ModuleFileIO { diff --git a/interfaces/kits/js/src/mod_fileio/properties/rmdir.h b/interfaces/kits/js/src/mod_fileio/properties/rmdir.h index 6e6e7bffeeda510f10ff9a79a5d08a8d7b830c4c..f509e732db318e70588814e622859ad67d1324e6 100644 --- a/interfaces/kits/js/src/mod_fileio/properties/rmdir.h +++ b/interfaces/kits/js/src/mod_fileio/properties/rmdir.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -16,7 +16,7 @@ #ifndef INTERFACES_KITS_JS_SRC_MOD_FILEIO_PROPERTIES_RMDIR_H #define INTERFACES_KITS_JS_SRC_MOD_FILEIO_PROPERTIES_RMDIR_H -#include "../../common/napi/n_val.h" +#include "n_val.h" namespace OHOS { namespace DistributedFS { diff --git a/interfaces/kits/js/src/mod_fileio/properties/rmdirent.cpp b/interfaces/kits/js/src/mod_fileio/properties/rmdirent.cpp index 2782d1b58d7a35913d4552f4664dbb0ce040215a..6f9cbfc26b78c3307851c4f9bedd8625a315a52a 100644 --- a/interfaces/kits/js/src/mod_fileio/properties/rmdirent.cpp +++ b/interfaces/kits/js/src/mod_fileio/properties/rmdirent.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 Huawei Device Co., Ltd. + * Copyright (c) 2022-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -17,14 +17,15 @@ #include #include -#include -#include #include #include -#include "../../common/napi/n_async/n_async_work_callback.h" -#include "../../common/napi/n_async/n_async_work_promise.h" -#include "../../common/napi/n_func_arg.h" +#include +#include + +#include "n_async_work_callback.h" +#include "n_async_work_promise.h" +#include "n_func_arg.h" namespace OHOS { namespace DistributedFS { diff --git a/interfaces/kits/js/src/mod_fileio/properties/rmdirent.h b/interfaces/kits/js/src/mod_fileio/properties/rmdirent.h index b63e528d1cf3ddff2a0323910d1848ec48589cea..07cb186db441a4799789981a74b81505339d353c 100644 --- a/interfaces/kits/js/src/mod_fileio/properties/rmdirent.h +++ b/interfaces/kits/js/src/mod_fileio/properties/rmdirent.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 Huawei Device Co., Ltd. + * Copyright (c) 2022-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -16,7 +16,7 @@ #ifndef INTERFACES_KITS_JS_SRC_MOD_FILEIO_PROPERTIES_RMDIRENT_H #define INTERFACES_KITS_JS_SRC_MOD_FILEIO_PROPERTIES_RMDIRENT_H -#include "../../common/napi/n_val.h" +#include "n_val.h" namespace OHOS { namespace DistributedFS { diff --git a/interfaces/kits/js/src/mod_fileio/properties/stat.cpp b/interfaces/kits/js/src/mod_fileio/properties/stat.cpp index 21d6f16fcbf804976dce8854ae26fa0072954c8a..29fc87c36b34409de7e4083465cbb462c99709ed 100644 --- a/interfaces/kits/js/src/mod_fileio/properties/stat.cpp +++ b/interfaces/kits/js/src/mod_fileio/properties/stat.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -17,15 +17,14 @@ #include #include -#include "../../common/napi/n_async/n_async_work_callback.h" -#include "../../common/napi/n_async/n_async_work_promise.h" -#include "../../common/napi/n_class.h" -#include "../../common/napi/n_func_arg.h" -#include "../../common/napi/n_val.h" -#include "../../common/uni_error.h" - -#include "../class_stat/stat_entity.h" -#include "../class_stat/stat_n_exporter.h" +#include "class_stat/stat_entity.h" +#include "class_stat/stat_n_exporter.h" +#include "n_async_work_callback.h" +#include "n_async_work_promise.h" +#include "n_class.h" +#include "n_func_arg.h" +#include "n_val.h" +#include "uni_error.h" namespace OHOS { namespace DistributedFS { diff --git a/interfaces/kits/js/src/mod_fileio/properties/stat.h b/interfaces/kits/js/src/mod_fileio/properties/stat.h index 8b16373e9b313c97cbfb9c3c21c06cf521edb82f..338074187bd898b7d2d7fe29da9b8e1240812e0b 100644 --- a/interfaces/kits/js/src/mod_fileio/properties/stat.h +++ b/interfaces/kits/js/src/mod_fileio/properties/stat.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -16,7 +16,7 @@ #ifndef INTERFACES_KITS_JS_SRC_MOD_FILEIO_PROPERTIES_STAT_H #define INTERFACES_KITS_JS_SRC_MOD_FILEIO_PROPERTIES_STAT_H -#include "../../common/napi/uni_header.h" +#include "uni_header.h" namespace OHOS { namespace DistributedFS { diff --git a/interfaces/kits/js/src/mod_fileio/properties/stat_v9.cpp b/interfaces/kits/js/src/mod_fileio/properties/stat_v9.cpp index 8c1f90b3bb082bff01baa3084a11750d06a19dca..18f31d29ca7b5d8ec8777c0fed7a37edd4acb644 100644 --- a/interfaces/kits/js/src/mod_fileio/properties/stat_v9.cpp +++ b/interfaces/kits/js/src/mod_fileio/properties/stat_v9.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022-2023 Huawei Device Co., Ltd. + * Copyright (c) 2022-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -17,16 +17,15 @@ #include #include -#include "../../common/file_helper/fd_guard.h" -#include "../../common/napi/n_async/n_async_work_callback.h" -#include "../../common/napi/n_async/n_async_work_promise.h" -#include "../../common/napi/n_class.h" -#include "../../common/napi/n_func_arg.h" -#include "../../common/napi/n_val.h" -#include "../../common/uni_error.h" - -#include "../class_stat_v9/stat_entity_v9.h" -#include "../class_stat_v9/stat_n_exporter_v9.h" +#include "class_stat_v9/stat_entity_v9.h" +#include "class_stat_v9/stat_n_exporter_v9.h" +#include "file_helper/fd_guard.h" +#include "n_async_work_callback.h" +#include "n_async_work_promise.h" +#include "n_class.h" +#include "n_func_arg.h" +#include "n_val.h" +#include "uni_error.h" namespace OHOS { namespace DistributedFS { diff --git a/interfaces/kits/js/src/mod_fileio/properties/stat_v9.h b/interfaces/kits/js/src/mod_fileio/properties/stat_v9.h index ecdd703cde3290f1030a36501a609ff1547f22e0..a4334652998ab47cd1477628eb85b293c7ceee8b 100644 --- a/interfaces/kits/js/src/mod_fileio/properties/stat_v9.h +++ b/interfaces/kits/js/src/mod_fileio/properties/stat_v9.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 Huawei Device Co., Ltd. + * Copyright (c) 2022-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -16,7 +16,7 @@ #ifndef INTERFACES_KITS_JS_SRC_MOD_FILEIO_PROPERTIES_STAT_V9_H #define INTERFACES_KITS_JS_SRC_MOD_FILEIO_PROPERTIES_STAT_V9_H -#include "../../common/napi/uni_header.h" +#include "uni_header.h" namespace OHOS { namespace DistributedFS { diff --git a/interfaces/kits/js/src/mod_fileio/properties/symlink.cpp b/interfaces/kits/js/src/mod_fileio/properties/symlink.cpp index c8b277b49dd9fd4888228f928481d041fff3dc1d..24123293b05385e59cdf57c135075aa115ab2230 100644 --- a/interfaces/kits/js/src/mod_fileio/properties/symlink.cpp +++ b/interfaces/kits/js/src/mod_fileio/properties/symlink.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021-2022 Huawei Device Co., Ltd. + * Copyright (c) 2021-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -14,14 +14,16 @@ */ #include "symlink.h" + #include #include #include #include -#include "../../common/napi/n_async/n_async_work_callback.h" -#include "../../common/napi/n_async/n_async_work_promise.h" -#include "../../common/napi/n_func_arg.h" +#include "n_async_work_callback.h" +#include "n_async_work_promise.h" +#include "n_func_arg.h" + namespace OHOS { namespace DistributedFS { namespace ModuleFileIO { diff --git a/interfaces/kits/js/src/mod_fileio/properties/symlink.h b/interfaces/kits/js/src/mod_fileio/properties/symlink.h index b770a27e874c3392e3ae46e112a6342140ed06f7..19db81aefa3cb282e6227841515f23cc9c96c5a9 100644 --- a/interfaces/kits/js/src/mod_fileio/properties/symlink.h +++ b/interfaces/kits/js/src/mod_fileio/properties/symlink.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -16,7 +16,7 @@ #ifndef INTERFACES_KITS_JS_SRC_MOD_FILEIO_PROPERTIES_SYMLINK_H #define INTERFACES_KITS_JS_SRC_MOD_FILEIO_PROPERTIES_SYMLINK_H -#include "../../common/napi/n_val.h" +#include "n_val.h" namespace OHOS { namespace DistributedFS { diff --git a/interfaces/kits/js/src/mod_fileio/properties/truncate.h b/interfaces/kits/js/src/mod_fileio/properties/truncate.h index b4f32e0264947345ea5803bec3148181aabf347f..faf6a68f62049ed838702d99c5734e9581477002 100644 --- a/interfaces/kits/js/src/mod_fileio/properties/truncate.h +++ b/interfaces/kits/js/src/mod_fileio/properties/truncate.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -16,10 +16,10 @@ #ifndef INTERFACES_KITS_JS_SRC_MOD_FILEIO_PROPERTIES_TRUNCATE_H #define INTERFACES_KITS_JS_SRC_MOD_FILEIO_PROPERTIES_TRUNCATE_H -#include "../../common/log.h" -#include "../../common/napi/n_async/n_async_work_callback.h" -#include "../../common/napi/n_async/n_async_work_promise.h" -#include "../../common/napi/n_func_arg.h" +#include "log.h" +#include "n_async_work_callback.h" +#include "n_async_work_promise.h" +#include "n_func_arg.h" namespace OHOS { namespace DistributedFS { diff --git a/interfaces/kits/js/src/mod_fileio/properties/truncate_v9.cpp b/interfaces/kits/js/src/mod_fileio/properties/truncate_v9.cpp index 1dc96c3cf156e227de3fe2107d58bb74e4be6d1c..e1e3452d1e615fb4ae9c2f6e5d31a9012f585574 100644 --- a/interfaces/kits/js/src/mod_fileio/properties/truncate_v9.cpp +++ b/interfaces/kits/js/src/mod_fileio/properties/truncate_v9.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022-2023 Huawei Device Co., Ltd. + * Copyright (c) 2022-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -19,7 +19,7 @@ #include #include -#include "../../common/file_helper/fd_guard.h" +#include "file_helper/fd_guard.h" namespace OHOS { namespace DistributedFS { diff --git a/interfaces/kits/js/src/mod_fileio/properties/truncate_v9.h b/interfaces/kits/js/src/mod_fileio/properties/truncate_v9.h index 2defe6b2de8530340271a26a6af79bd09971f755..bd6fceb50d9a1f2eeb0d231859086b3200f7f3fc 100644 --- a/interfaces/kits/js/src/mod_fileio/properties/truncate_v9.h +++ b/interfaces/kits/js/src/mod_fileio/properties/truncate_v9.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 Huawei Device Co., Ltd. + * Copyright (c) 2022-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -16,10 +16,10 @@ #ifndef INTERFACES_KITS_JS_SRC_MOD_FILEIO_PROPERTIES_TRUNCATE_V9_H #define INTERFACES_KITS_JS_SRC_MOD_FILEIO_PROPERTIES_TRUNCATE_V9_H -#include "../../common/log.h" -#include "../../common/napi/n_async/n_async_work_callback.h" -#include "../../common/napi/n_async/n_async_work_promise.h" -#include "../../common/napi/n_func_arg.h" +#include "log.h" +#include "n_async_work_callback.h" +#include "n_async_work_promise.h" +#include "n_func_arg.h" namespace OHOS { namespace DistributedFS { diff --git a/interfaces/kits/js/src/mod_fileio/properties/watcher.cpp b/interfaces/kits/js/src/mod_fileio/properties/watcher.cpp index 822043cb034396463663c08c2b1d8b4fac34c9c9..c95c5c0fff6395f0606bd85508f346e3a9adf0af 100644 --- a/interfaces/kits/js/src/mod_fileio/properties/watcher.cpp +++ b/interfaces/kits/js/src/mod_fileio/properties/watcher.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -20,15 +20,15 @@ #include #include -#include "../../common/napi/n_async/n_ref.h" -#include "../../common/napi/n_class.h" -#include "../../common/napi/n_func_arg.h" -#include "../../common/napi/n_val.h" -#include "../../common/uni_error.h" +#include "class_watcher/watcher_entity.h" +#include "class_watcher/watcher_n_exporter.h" #include "file_utils.h" +#include "n_class.h" +#include "n_func_arg.h" +#include "n_ref.h" +#include "n_val.h" +#include "uni_error.h" -#include "../class_watcher/watcher_entity.h" -#include "../class_watcher/watcher_n_exporter.h" namespace OHOS { namespace DistributedFS { namespace ModuleFileIO { diff --git a/interfaces/kits/js/src/mod_fileio/properties/watcher.h b/interfaces/kits/js/src/mod_fileio/properties/watcher.h index 45c100cb21057e0a0711212df5ec9846985aebaf..0c85afe620d3434084d4fa49a7804b6012fada5b 100644 --- a/interfaces/kits/js/src/mod_fileio/properties/watcher.h +++ b/interfaces/kits/js/src/mod_fileio/properties/watcher.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -17,7 +17,7 @@ #define INTERFACES_KITS_JS_SRC_MOD_FILEIO_PROPERTIES_WATCHER_H #include -#include "../../common/napi/n_val.h" +#include "n_val.h" namespace OHOS { namespace DistributedFS { diff --git a/interfaces/kits/js/src/mod_fs/ani/bind_function_class.cpp b/interfaces/kits/js/src/mod_fs/ani/bind_function_class.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f8da76c82eceb3b8b1dc01ce8ba6db462bd5668c --- /dev/null +++ b/interfaces/kits/js/src/mod_fs/ani/bind_function_class.cpp @@ -0,0 +1,147 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include + +#include + +#include "access_ani.h" +#include "ani_signature.h" +#include "bind_function.h" +#include "close_ani.h" +#include "copy_file_ani.h" +#include "file_ani.h" +#include "listfile_ani.h" +#include "mkdir_ani.h" +#include "move_ani.h" +#include "read_ani.h" +#include "rmdir_ani.h" +#include "open_ani.h" +#include "read_text_ani.h" +#include "stat_ani.h" +#include "truncate_ani.h" +#include "unlink_ani.h" +#include "write_ani.h" + +using namespace OHOS::FileManagement::ModuleFileIO::ANI; +using namespace OHOS::FileManagement::ModuleFileIO::ANI::AniSignature; + +static ani_status BindFileMethods(ani_env *env) +{ + auto classDesc = FS::FileInner::classDesc.c_str(); + + std::array methods = { + ani_native_function { "getParent", nullptr, reinterpret_cast(FileAni::GetParent) }, + ani_native_function { "lockSync", nullptr, reinterpret_cast(FileAni::LockSync) }, + ani_native_function { "tryLock", nullptr, reinterpret_cast(FileAni::TryLock) }, + ani_native_function { "unlock", nullptr, reinterpret_cast(FileAni::UnLock) }, + }; + + return BindClass(env, classDesc, methods); +} + +static ani_status BindStatClassMethods(ani_env *env) +{ + auto classDesc = FS::StatInner::classDesc.c_str(); + + std::array methods = { + ani_native_function { "isBlockDevice", nullptr, reinterpret_cast(StatAni::IsBlockDevice) }, + ani_native_function { "isCharacterDevice", nullptr, reinterpret_cast(StatAni::IsCharacterDevice) }, + ani_native_function { "isDirectory", nullptr, reinterpret_cast(StatAni::IsDirectory) }, + ani_native_function { "isFIFO", nullptr, reinterpret_cast(StatAni::IsFIFO) }, + ani_native_function { "isFile", nullptr, reinterpret_cast(StatAni::IsFile) }, + ani_native_function { "isSocket", nullptr, reinterpret_cast(StatAni::IsSocket) }, + ani_native_function { "isSymbolicLink", nullptr, reinterpret_cast(StatAni::IsSymbolicLink) }, + }; + + return BindClass(env, classDesc, methods); +} + +const static string mkdirCtorSig0 = Builder::BuildSignatureDescriptor({ BuiltInTypes::stringType }); +const static string mkdirCtorSig1 = + Builder::BuildSignatureDescriptor({ BuiltInTypes::stringType, BasicTypes::booleanType }); + +static ani_status BindStaticMethods(ani_env *env) +{ + auto classDesc = Impl::FileIoImpl::classDesc.c_str(); + + std::array methods = { + ani_native_function { "closeSync", nullptr, reinterpret_cast(CloseAni::CloseSync) }, + ani_native_function { "copyFileSync", nullptr, reinterpret_cast(CopyFileAni::CopyFileSync) }, + ani_native_function { "doAccessSync", nullptr, reinterpret_cast(AccessAni::AccessSync3) }, + ani_native_function { "listFileSync", nullptr, reinterpret_cast(ListFileAni::ListFileSync) }, + ani_native_function { "mkdirSync", mkdirCtorSig0.c_str(), reinterpret_cast(MkdirkAni::MkdirSync0) }, + ani_native_function { "mkdirSync", mkdirCtorSig1.c_str(), reinterpret_cast(MkdirkAni::MkdirSync1) }, + ani_native_function { "moveFileSync", nullptr, reinterpret_cast(MoveAni::MoveFileSync) }, + ani_native_function { "openSync", nullptr, reinterpret_cast(OpenAni::OpenSync) }, + ani_native_function { "readSync", nullptr, reinterpret_cast(ReadAni::ReadSync) }, + ani_native_function { "readTextSync", nullptr, reinterpret_cast(ReadTextAni::ReadTextSync) }, + ani_native_function { "rmdirSync", nullptr, reinterpret_cast(RmdirAni::RmdirSync) }, + ani_native_function { "statSync", nullptr, reinterpret_cast(StatAni::StatSync) }, + ani_native_function { "truncateSync", nullptr, reinterpret_cast(TruncateAni::TruncateSync) }, + ani_native_function { "unlinkSync", nullptr, reinterpret_cast(UnlinkAni::UnlinkSync) }, + ani_native_function { "writeSync", nullptr, reinterpret_cast(WriteAni::WriteSync) }, + }; + return BindClass(env, classDesc, methods); +} + +static ani_status DoBindMethods(ani_env *env) +{ + ani_status status; + if ((status = BindStaticMethods(env)) != ANI_OK) { + HILOGE("Cannot bind native static methods for BindStaticMethods!"); + return status; + }; + + if ((status = BindFileMethods(env)) != ANI_OK) { + HILOGE("Cannot bind native methods for file Class"); + return status; + }; + + if ((status = BindStatClassMethods(env)) != ANI_OK) { + HILOGE("Cannot bind native methods for Stat Class!"); + return status; + }; + + return ANI_OK; +} + +ANI_EXPORT ani_status ANI_Constructor(ani_vm *vm, uint32_t *result) +{ + if (vm == nullptr) { + HILOGE("Invalid parameter vm"); + return ANI_INVALID_ARGS; + } + + if (result == nullptr) { + HILOGE("Invalid parameter result"); + return ANI_INVALID_ARGS; + } + + ani_env *env; + ani_status status = vm->GetEnv(ANI_VERSION_1, &env); + if (status != ANI_OK) { + HILOGE("Invalid ani version!"); + return ANI_INVALID_VERSION; + } + + status = DoBindMethods(env); + if (status != ANI_OK) { + return status; + } + + *result = ANI_VERSION_1; + return ANI_OK; +} diff --git a/interfaces/kits/js/src/mod_fs/ani/ets/@ohos.file.fs.ets b/interfaces/kits/js/src/mod_fs/ani/ets/@ohos.file.fs.ets new file mode 100644 index 0000000000000000000000000000000000000000..5de05d13c16f74668df53433be2c1f8fdb6bccda --- /dev/null +++ b/interfaces/kits/js/src/mod_fs/ani/ets/@ohos.file.fs.ets @@ -0,0 +1,2173 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { BusinessError, AsyncCallback } from '@ohos.base'; +// import stream from '@ohos.util.stream'; + +const UNKNOWN_ERR: number = 13900042 +const UNKNOWN_MSG: string = "Unknown error" + +function createBusinessError(code: number, msg: string): BusinessError { + let err = new BusinessError(); + err.code = code; + err.message = msg; + return err; +} + +namespace fileIo { + export namespace OpenMode { + export const READ_ONLY = 0o0; + export const WRITE_ONLY = 0o1; + export const READ_WRITE = 0o2; + export const CREATE = 0o100; + export const TRUNC = 0o1000; + export const APPEND = 0o2000; + export const NONBLOCK = 0o4000; + export const DIR = 0o200000; + export const NOFOLLOW = 0o400000; + export const SYNC = 0o4010000; + } + +function access(path: string, mode?: AccessModeType): Promise { + return new Promise((resolve: (result: boolean) => void, reject: (e: BusinessError) => void) => { + let promise = taskpool.execute((path: string, mode?: AccessModeType): boolean => { + return FileIoImpl.doAccessSync(path, mode); + }, path, mode); + promise.then((ret: NullishType): void => { + let result = ret as boolean; + resolve(result); + }).catch((e: BusinessError): void => { + reject(e); + }); + }); +} + +function access(path: string, callback: AsyncCallback): void { + let promise = taskpool.execute((path: string): boolean => { + return FileIoImpl.doAccessSync(path); + }, path); + promise.then((ret: NullishType): void => { + let e = new BusinessError(); + e.code = 0; + let result = ret as boolean; + callback(e, result); + }).catch((e: BusinessError): void => { + callback(e, false); + }); +} + +function access(path: string, mode: AccessModeType, flag: AccessFlagType): Promise { + return new Promise((resolve: (result: boolean) => void, reject: (e: BusinessError) => void) => { + let promise = taskpool.execute((path: string, mode: AccessModeType, flag: AccessFlagType): boolean => { + return FileIoImpl.doAccessSync(path, mode, flag); + }, path, mode, flag); + promise.then((ret: NullishType): void => { + let result = ret as boolean; + resolve(result); + }).catch((e: BusinessError): void => { + reject(e); + }); + }) +} + +function accessSync(path: string, mode?: AccessModeType): boolean { + return FileIoImpl.doAccessSync(path, mode); +} + +function accessSync(path: string, mode: AccessModeType, flag: AccessFlagType): boolean { + return FileIoImpl.doAccessSync(path, mode, flag); +} + +function close(file: number | File): Promise { + return new Promise((resolve: (result: undefined) => void, reject: (e: BusinessError) => void): void => { + let promise = taskpool.execute((file: number | File): undefined => FileIoImpl.closeSync(file), file); + promise.then((ret: NullishType): void => { + resolve(undefined); + }).catch((e: BusinessError): void => { + reject(e); + }); + }); +} + +function close(file: number | File, callback: AsyncCallback): void { + let promise = taskpool.execute((file: number | File): undefined => FileIoImpl.closeSync(file), file); + promise.then((ret: NullishType): void => { + let e = new BusinessError(); + e.code = 0; + callback(e, undefined); + }).catch((e: BusinessError): void => { + callback(e, undefined); + }); +} + +function closeSync(file: number | File): void { + return FileIoImpl.closeSync(file) +} + +function connectDfs(networkId: string, listeners: DfsListeners): Promise { + return new Promise((resolve: (result: undefined) => void, reject: (e: BusinessError) => void): void => { + let promise = taskpool.execute((networkId: string, listeners: DfsListeners): void => + FileIoImpl.connectDfs(networkId, listeners), networkId, listeners); + promise.then((): void => { + resolve(undefined); + }).catch((e: BusinessError): void => { + reject(e); + }); + }); +} + +function disconnectDfs(networkId: string): Promise { + return new Promise((resolve: (result: undefined) => void, reject: (e: BusinessError) => void): void => { + let promise = taskpool.execute((networkId: string): void => FileIoImpl.disConnectDfs(networkId), networkId); + promise.then((): void => { + resolve(undefined); + }).catch((e: BusinessError): void => { + reject(e); + }); + }); +} + +function getxattrSync(path: string, key: string): string { + return FileIoImpl.getxattrSync(path, key) +} + +function getxattr(path: string, key: string): Promise { + return new Promise((resolve: (result: string) => void, reject: (e: BusinessError) => void): void => { + let promise = taskpool.execute((path: string, key: string): string => { + return FileIoImpl.getxattrSync(path, key); + }, path, key); + promise.then((ret: NullishType): void => { + let result = ret as string; + resolve(result); + }).catch((e: BusinessError): void => { + reject(e); + }); + }); +} + +function dup(fd: number): File { + return FileIoImpl.dup(fd); +} + +function copyDirSync(src: string, dest: string, mode?: number): void { + return FileIoImpl.copyDirSync(src, dest, mode); +} + +function copyDir(src: string, dest: string, mode?: number): Promise { + return new Promise((resolve: (result: undefined) => void, + reject: (e: BusinessError>) => void): void => { + let promise = taskpool.execute((src: string, dest: string, mode?: number): undefined => + FileIoImpl.copyDirSync(src, dest, mode), src, dest, mode); + promise.then((ret: NullishType): void => { + resolve(undefined); + }).catch((e: BusinessError>): void => { + reject(e); + }); + }); +} + +function copyDir(src: string, dest: string, callback: AsyncCallback>): void { + let promise = taskpool.execute((src: string, dest: string): undefined => + FileIoImpl.copyDirSync(src, dest), src, dest); + promise.then((ret: NullishType): void => { + let e = new BusinessError>(); + e.code = 0; + e.data = new Array(0); + callback(e, undefined); + }).catch((e: BusinessError>): void => { + callback(e, undefined); + }); +} + +function copyDir(src: string, dest: string, mode: number, callback: AsyncCallback>): void { + let promise = taskpool.execute((src: string, dest: string, mode: number): undefined => + FileIoImpl.copyDirSync(src, dest, mode), src, dest, mode); + promise.then((ret: NullishType): void => { + let e = new BusinessError>(); + e.code = 0; + e.data = new Array(0); + callback(e, undefined); + }).catch((e: BusinessError>): void => { + callback(e, undefined); + }); +} + +function copyDir(arg0: Object, arg1: Object, arg2: NullishType, arg3: NullishType): void { + let src = arg0 as string; + let dest = arg1 as string; + if (typeof arg2 === 'number' && typeof arg3 === 'function') { + let mode: number = 0; + try { + mode = arg2 as number; + } catch (error) { + mode = (arg2 as int) + 0; + } + let callback = arg3 as AsyncCallback>; + copyDir(src, dest, mode, callback); + return; + } + if (typeof arg2 === 'function') { + let callback = arg2 as AsyncCallback>; + copyDir(src, dest, callback); + return; + } +} + +function mkdirSync(path: string): void { + return FileIoImpl.mkdirSync(path) +} + +function fdatasyncSync(fd: number): void { + return FileIoImpl.fdatasyncSync(fd) +} + +function fdatasync(fd: number): Promise { + return new Promise((resolve: (result: undefined) => void, reject: (e: BusinessError) => void): void => { + let promise = taskpool.execute((fd: number): undefined => FileIoImpl.fdatasyncSync(fd), fd); + promise.then((ret: NullishType): void => { + resolve(undefined); + }).catch((e: BusinessError): void => { + reject(e as BusinessError); + }); + }); +} + +function fdatasync(fd: number, callback: AsyncCallback): void { + let promise = taskpool.execute((fd: number): undefined => FileIoImpl.fdatasyncSync(fd), fd); + promise.then((ret: NullishType): void => { + let e = new BusinessError(); + e.code = 0; + callback(e, undefined); + }).catch((e: BusinessError): void => { + callback(e, undefined); + }); +} + +function mkdirSync(path: string, recursion: boolean): void { + return FileIoImpl.mkdirSync(path, recursion) +} + +function mkdirSync1(path: string): undefined { + FileIoImpl.mkdirSync(path); + return undefined; +} + +function mkdirSync2(path: string, recursion: boolean): undefined { + FileIoImpl.mkdirSync(path, recursion); + return undefined; +} + +function mkdir(path: string): Promise { + return new Promise((resolve: (result: undefined) => void, reject: (e: BusinessError) => void): void => { + let promise = taskpool.execute((path: string): undefined => mkdirSync1(path), path); + promise.then((ret: NullishType): void => { + resolve(undefined); + }).catch((e: BusinessError): void => { + reject(e as BusinessError); + }); + }); +} + +function mkdir(path: string, callback: AsyncCallback): void { + let promise = taskpool.execute((path: string): undefined => mkdirSync1(path), path); + promise.then((ret: NullishType): void => { + let e = new BusinessError(); + e.code = 0; + callback(e, undefined); + }).catch((e: BusinessError): void => { + callback(e, undefined); + }); +} + +function mkdir(path: string, recursion: boolean): Promise { + return new Promise((resolve: (result: undefined) => void, reject: (e: BusinessError) => void): void => { + let promise = taskpool.execute((path: string, recursion: boolean): undefined => + mkdirSync2(path, recursion), path, recursion); + promise.then((ret: NullishType): void => { + resolve(undefined); + }).catch((e: NullishType): void => { + reject(e as BusinessError); + }); + }); +} + +function mkdir(path: string, recursion: boolean, callback: AsyncCallback): void { + let promise = taskpool.execute((path: string, recursion: boolean): undefined => + mkdirSync2(path, recursion), path, recursion); + promise.then((ret: NullishType): void => { + let e = new BusinessError(); + e.code = 0; + callback(e, undefined); + }).catch((e: BusinessError): void => { + callback(e, undefined); + }); +} + +function moveDirSync(src: string, dest: string, mode?: number): void { + return FileIoImpl.movedirSync(src, dest, mode) +} + +function moveDir(src: string, dest: string, mode?: number): Promise { + return new Promise((resolve: (result: undefined) => void, + reject: (e: BusinessError>) => void): void => { + let promise = taskpool.execute((src: string, dest: string, mode?: number): undefined => { + return FileIoImpl.movedirSync(src, dest, mode); + }, src, dest, mode); + promise.then((ret: NullishType): void => { + resolve(undefined); + }).catch((e: BusinessError>): void => { + reject(e); + }); + }) +} + +function moveDir(src: string, dest: string, callback: AsyncCallback>): void { + let promise = taskpool.execute((src: string, dest: string): undefined => { + return FileIoImpl.movedirSync(src, dest); + }, src, dest); + promise.then((ret: NullishType): void => { + let e = new BusinessError>(); + e.code = 0; + e.data = new Array(0); + callback(e, undefined); + }).catch((e: BusinessError>): void => { + callback(e, undefined); + }); +} + +function moveDir(src: string, dest: string, mode: number, callback: AsyncCallback>): void { + let promise = taskpool.execute((src: string, dest: string, mode: number): undefined => { + return FileIoImpl.movedirSync(src, dest, mode); + }, src, dest, mode); + promise.then((ret: NullishType): void => { + let e = new BusinessError>(); + e.code = 0; + e.data = new Array(0); + callback(e, undefined); + }).catch((e: BusinessError>): void => { + callback(e, undefined); + }); +} + +function moveDir(arg0: Object, arg1: Object, arg2: NullishType, arg3: NullishType): void { + let src = arg0 as string; + let dest = arg1 as string; + if (typeof arg2 === 'number' && typeof arg3 === 'function') { + let mode: number = 0; + try { + mode = arg2 as number; + } catch (error) { + mode = (arg2 as int) + 0; + } + let callback = arg3 as AsyncCallback>; + moveDir(src, dest, mode, callback); + return; + } + if (typeof arg2 === 'function') { + let callback = arg2 as AsyncCallback>; + moveDir(src, dest, callback); + return; + } +} + +function mkdtempSync(prefix: string): string { + return FileIoImpl.mkdtempSync(prefix); +} + +function mkdtemp(prefix: string): Promise { + return new Promise((resolve: (result: string) => void, reject: (e: BusinessError) => void): void => { + let promise = taskpool.execute((prefix: string): string => { + return FileIoImpl.mkdtempSync(prefix); + }, prefix); + promise.then((ret: NullishType): void => { + let result = ret as string; + resolve(result); + }).catch((e: BusinessError): void => { + reject(e); + }); + }); +} + +function mkdtemp(prefix: string, callback: AsyncCallback): void { + let promise = taskpool.execute((prefix: string): string => { + return FileIoImpl.mkdtempSync(prefix); + }, prefix); + promise.then((ret: NullishType): void => { + let e = new BusinessError(); + e.code = 0; + let result = ret as string; + callback(e, result); + }).catch((e: BusinessError): void => { + callback(e, ""); + }); +} + +function moveFileSync(src: string, dest: string, mode?: number): void { + return FileIoImpl.moveFileSync(src, dest, mode); +} + +function moveFile(src: string, dest: string, mode?: number): Promise { + return new Promise((resolve: (result: undefined) => void, reject: (e: BusinessError) => void): void => { + let promise = taskpool.execute((src: string, dest: string, mode?: number): undefined => { + return FileIoImpl.moveFileSync(src, dest, mode); + }, src, dest, mode); + promise.then((ret: NullishType): void => { + resolve(undefined); + }).catch((e: BusinessError): void => { + reject(e); + }); + }); +} + +function moveFile(src: string, dest: string, mode: number, callback: AsyncCallback): void { + let promise = taskpool.execute((src: string, dest: string, mode: number): undefined => { + return FileIoImpl.moveFileSync(src, dest, mode); + }, src, dest, mode); + promise.then((ret: NullishType): void => { + let e = new BusinessError(); + e.code = 0; + callback(e, undefined); + }).catch((e: BusinessError): void => { + callback(e, undefined); + }); +} + +function moveFile(src: string, dest: string, callback: AsyncCallback): void { + let promise = taskpool.execute((src: string, dest: string): undefined => { + return FileIoImpl.moveFileSync(src, dest); + }, src, dest); + promise.then((ret: NullishType): void => { + let e = new BusinessError(); + e.code = 0; + callback(e, undefined); + }).catch((e: BusinessError): void => { + callback(e, undefined); + }); +} + +function openSync(path: string, mode?: number): File { + return FileIoImpl.openSync(path, mode); +} + +function open(path: String, mode?: number): Promise { + return new Promise((resolve: (result: File) => void, reject: (e: BusinessError) => void) => { + let promise = taskpool.execute((path: String, mode?: number): File => { + return FileIoImpl.openSync(path, mode); + },path, mode); + promise.then((ret: NullishType): void => { + let file = ret as File; + resolve(file); + }).catch((e: BusinessError): void => { + reject(e); + }); + }); +} + +function open(path: String, mode: number, callback: AsyncCallback): void { + let promise = taskpool.execute((path: String, mode: number): File => { + return FileIoImpl.openSync(path, mode); + }, path, mode); + promise.then((ret: NullishType): void => { + let e = new BusinessError(); + e.code = 0; + let file = ret as File; + callback(e, file); + }).catch((e: BusinessError): void => { + let f: File = new FileInner(0); + callback(e, f); + }); +} + +function open(path: String, callback: AsyncCallback): void { + let promise = taskpool.execute((path: String): File => { + return FileIoImpl.openSync(path); + }, path); + promise.then((ret: NullishType): void => { + let e = new BusinessError(); + e.code = 0; + let file = ret as File; + callback(e, file); + }).catch((e: BusinessError): void => { + let f: File = new FileInner(0); + callback(e, f); + }); +} + +function writeSync(fd: number, buffer: string | ArrayBuffer, options?: WriteOptions): number { + return FileIoImpl.writeSync(fd, buffer, options); +} + +function write(fd: number, buffer: string | ArrayBuffer, options?: WriteOptions): Promise { + return new Promise((resolve: (result: number) => void, reject: (e: BusinessError) => void) => { + let promise = taskpool.execute((fd: number, buffer: string | ArrayBuffer, options?: WriteOptions): number => { + return FileIoImpl.writeSync(fd, buffer, options); + }, fd, buffer, options); + promise.then((ret: NullishType): void => { + let result = ret as number + resolve(result); + }).catch((e: BusinessError): void => { + reject(e); + }); + }); +} + +function write(fd: number, buffer: string | ArrayBuffer, options: WriteOptions, + callback: AsyncCallback): void { + let promise = taskpool.execute((fd: number, buffer: string | ArrayBuffer, options: WriteOptions): number => { + return FileIoImpl.writeSync(fd, buffer, options); + }, fd, buffer, options); + promise.then((ret: NullishType): void => { + let e = new BusinessError(); + e.code = 0; + let result = ret as number; + callback(e, result); + }).catch((e: BusinessError): void => { + callback(e, 0); + }); +} + +function write(fd: number, buffer: string | ArrayBuffer, callback: AsyncCallback): void { + let promise = taskpool.execute((fd: number, buffer: string | ArrayBuffer): number => { + return FileIoImpl.writeSync(fd, buffer); + }, fd, buffer); + promise.then((ret: NullishType): void => { + let e = new BusinessError(); + e.code = 0; + let result = ret as number; + callback(e, result); + }).catch((e: BusinessError): void => { + callback(e, 0); + }); +} + +function readSync(fd: number, buffer: ArrayBuffer, options?: ReadOptions): number { + return FileIoImpl.readSync(fd, buffer, options) +} + +function read(fd: number, buffer: ArrayBuffer, options?: ReadOptions): Promise { + return new Promise((resolve: (result: number) => void, reject: (e: BusinessError) => void) => { + let promise = taskpool.execute((fd: number, buffer: ArrayBuffer, options?: ReadOptions): number => { + return FileIoImpl.readSync(fd, buffer, options) + }, fd, buffer, options); + promise.then((ret: NullishType) => { + let result = ret as number; + resolve(result); + }).catch((e: BusinessError): void => { + reject(e); + }); + }); +} + +function read(fd: number, buffer: ArrayBuffer, callback: AsyncCallback): void { + let promise = taskpool.execute((fd: number, buffer: ArrayBuffer): number => { + return FileIoImpl.readSync(fd, buffer); + }, fd, buffer); + promise.then((ret: NullishType): void => { + let e = new BusinessError(); + e.code = 0; + let result = ret as number; + callback(e, result); + }).catch((e: BusinessError): void => { + callback(e, 0); + }); +} + +function read(fd: number, buffer: ArrayBuffer, options: ReadOptions, callback: AsyncCallback): void { + let promise = taskpool.execute((fd: number, buffer: ArrayBuffer, options: ReadOptions): number => { + return FileIoImpl.readSync(fd, buffer, options); + }, fd, buffer, options); + promise.then((ret: NullishType): void => { + let e = new BusinessError(); + e.code = 0; + let result = ret as number; + callback(e, result); + }).catch((e: BusinessError): void => { + callback(e, 0); + }); +} + +function readLinesSync(filePath: string, options?: Options): ReaderIterator { + return FileIoImpl.readlinesSync(filePath, options) +} + +function readLines(filePath: string, options?: Options): Promise { + return new Promise((resolve: (result: ReaderIterator) => void, + reject: (e: BusinessError) => void) => { + let promise = taskpool.execute((filePath: string, options?: Options): ReaderIterator => { + return FileIoImpl.readlinesSync(filePath, options); + }, filePath, options); + promise.then((ret: NullishType): void => { + let it = ret as ReaderIterator; + resolve(it); + }).catch((e: BusinessError): void => { + reject(e); + }); + }); +} + +function readLines(filePath: string, callback: AsyncCallback): void { + let promise = taskpool.execute((filePath: string): ReaderIterator => { + return FileIoImpl.readlinesSync(filePath); + }, filePath); + promise.then((ret: NullishType): void => { + let e = new BusinessError(); + e.code = 0; + let it = ret as ReaderIterator; + callback(e, it); + }).catch((e: BusinessError): void => { + let r: ReaderIterator = new ReaderIteratorInner(0); + callback(e, r); + }); +} + +function readLines(filePath: string, options: Options, callback: AsyncCallback): void { + let promise = taskpool.execute((filePath: string, options: Options): ReaderIterator => { + return FileIoImpl.readlinesSync(filePath, options); + }, filePath, options); + promise.then((ret: NullishType): void => { + let e = new BusinessError(); + e.code = 0; + let it = ret as ReaderIterator; + callback(e, it); + }).catch((e: BusinessError): void => { + let r: ReaderIterator = new ReaderIteratorInner(0); + callback(e, r); + }); +} + +function rmdirSync(path: string): void { + return FileIoImpl.rmdirSync(path) +} + +function rmdir(path: string): Promise { + return new Promise((resolve: (result: undefined) => void, + reject: (e: BusinessError) => void): void => { + let promise = taskpool.execute((path: string): void => FileIoImpl.rmdirSync(path), path); + promise.then((ret: NullishType) => { + resolve(undefined); + }).catch((e: BusinessError): void => { + reject(e); + }); + }); +} + +function rmdir(path: string, callback: AsyncCallback): void { + let promise = taskpool.execute((path: string): void => FileIoImpl.rmdirSync(path), path); + promise.then((ret: NullishType) => { + let e = new BusinessError(); + e.code = 0; + callback(e, undefined); + }).catch((e: BusinessError): void => { + callback(e, undefined); + }); +} + +function truncateSync(file: string | number, len?: number): void { + return FileIoImpl.truncateSync(file, len) +} + +function truncate(file: string | number, len?: number): Promise { + return new Promise((resolve: (result: undefined) => void, reject: (e: BusinessError) => void): void => { + let promise = taskpool.execute((file: string | number, len?: number): undefined => { + return FileIoImpl.truncateSync(file, len); + }, file, len); + promise.then((ret: NullishType): void => { + resolve(undefined); + }).catch((e: BusinessError): void => { + reject(e); + }); + }) +} + +function truncate(file: string | number, callback: AsyncCallback): void { + let promise = taskpool.execute((file: string | number): undefined => { + return FileIoImpl.truncateSync(file); + }, file); + promise.then((ret: NullishType): void => { + let e = new BusinessError(); + e.code = 0; + callback(e, undefined); + }).catch((e: BusinessError): void => { + callback(e, undefined); + }); +} + +function truncate(file: string | number, len: number, callback: AsyncCallback): void { + let promise = taskpool.execute((file: string | number, len: number): undefined => { + return FileIoImpl.truncateSync(file, len); + }, file, len); + promise.then((ret: NullishType): void => { + let e = new BusinessError(); + e.code = 0; + callback(e, undefined); + }).catch((e: BusinessError): void => { + callback(e, undefined); + }); +} + +function unlinkSync(path: string): void { + return FileIoImpl.unlinkSync(path) +} + +function unlink(path: string): Promise { + return new Promise((resolve: (result: undefined) => void, + reject: (e: BusinessError) => void): void => { + let promise = taskpool.execute((path: string): undefined => unlinkSync(path), path); + promise.then((ret: NullishType): void => { + resolve(undefined); + }).catch((e: BusinessError): void => { + reject(e); + }); + }); +} + +function unlink(path: string, callback: AsyncCallback): void { + let promise = taskpool.execute((path: string): undefined => unlinkSync(path), path); + promise.then((ret: NullishType): void => { + let e = new BusinessError(); + e.code = 0; + callback(e, undefined); + }).catch((e: BusinessError): void => { + callback(e, undefined); + }); +} + +function readText(filePath: string, options?: ReadTextOptions): Promise { + return new Promise((resolve: (result: string) => void, reject: (e: BusinessError) => void) => { + let promise = taskpool.execute((filePath: string, options?: ReadTextOptions): string => { + return FileIoImpl.readTextSync(filePath, options); + }, filePath, options); + promise.then((ret: NullishType): void => { + let r = ret as string; + resolve(r); + }).catch((e: BusinessError): void => { + reject(e); + }); + }); +} + +function readText(filePath: string, callback: AsyncCallback): void { + let promise = taskpool.execute((filePath: string): string => { + return FileIoImpl.readTextSync(filePath); + }, filePath); + promise.then((ret: NullishType): void => { + let e = new BusinessError(); + e.code = 0; + let r = ret as string; + callback(e, r); + }).catch((e: BusinessError): void => { + callback(e, ""); + }); +} + +function readText(filePath: string, options: ReadTextOptions, callback: AsyncCallback): void { + let promise = taskpool.execute((filePath: string, options: ReadTextOptions): string => { + return FileIoImpl.readTextSync(filePath, options); + }, filePath, options); + promise.then((ret: NullishType): void => { + let e = new BusinessError(); + e.code = 0; + let r = ret as string; + callback(e, r); + }).catch((e: BusinessError): void => { + callback(e, ""); + }); +} + +function readTextSync(filePath: string, options?: ReadTextOptions): string { + return FileIoImpl.readTextSync(filePath, options); +} + +function listFile(path: string, options?: ListFileOptions): Promise { + return new Promise((resolve: (result: string[]) => void, reject: (e: BusinessError) => void) => { + let promise = taskpool.execute((path: string, options?: ListFileOptions): string[] => { + return FileIoImpl.listFileSync(path, options); + }, path, options); + promise.then((ret: NullishType): void => { + let r = ret as string[]; + resolve(r); + }).catch((e: BusinessError): void => { + reject(e); + }); + }); +} + +function listFile(path: string, callback: AsyncCallback): void { + let promise = taskpool.execute((path: string): string[] => { + return FileIoImpl.listFileSync(path); + }, path); + promise.then((ret: NullishType): void => { + let e = new BusinessError(); + e.code = 0; + let r = ret as string[]; + callback(e, r); + }).catch((e: BusinessError): void => { + callback(e, []); + }); +} + +function listFile(path: string, options: ListFileOptions, callback: AsyncCallback): void { + let promise = taskpool.execute((path: string, options: ListFileOptions): string[] => { + return FileIoImpl.listFileSync(path, options); + }, path, options); + promise.then((ret: NullishType): void => { + let e = new BusinessError(); + e.code = 0; + let r = ret as string[]; + callback(e, r); + }).catch((e: BusinessError): void => { + callback(e, []); + }); +} + +function listFileSync(path: string, options?: ListFileOptions): string[] { + return FileIoImpl.listFileSync(path, options); +} + +function copyFileSync(src: string | number, dest: string | number, mode?: number): void { + return FileIoImpl.copyFileSync(src, dest, mode) +} + +function statSync(file: string | number): Stat { + return FileIoImpl.statSync(file) +} + +function stat(file: string | number): Promise { + return new Promise((resolve: (result: Stat) => void, reject: (e: BusinessError) => void) => { + let promise = taskpool.execute((file: string | number): Stat => { + return FileIoImpl.statSync(file); + }, file); + promise.then((ret: NullishType): void => { + let r = ret as Stat; + resolve(r); + }).catch((e: BusinessError): void => { + reject(e); + }); + }); +} + +function stat(file: string | number, callback: AsyncCallback): void { + let p = taskpool.execute((file: string | number): Stat => { + return FileIoImpl.statSync(file); + }, file); + p.then((ret: NullishType): void => { + let e = new BusinessError(); + e.code = 0; + let r = ret as Stat; + callback(e, r); + }).catch((e: BusinessError): void => { + callback(e, new StatInner(0)); + }); +} + +function fsyncSync(fd: number): void { + return FileIoImpl.fsyncSync(fd); +} + +function fsync(fd: number): Promise { + return new Promise((resolve: (result: undefined) => void, reject: (e: BusinessError) => void): void => { + let promise = taskpool.execute((fd: number): undefined => { + return FileIoImpl.fsyncSync(fd); + }, fd); + promise.then((ret: NullishType): void => { + resolve(undefined); + }).catch((e: BusinessError): void => { + reject(e); + }); + }); +} + +function fsync(fd: number, callback: AsyncCallback): void { + let promise = taskpool.execute((fd: number): undefined => { + return FileIoImpl.fsyncSync(fd); + }, fd); + promise.then((ret: NullishType): void => { + let e = new BusinessError(); + e.code = 0; + callback(e, undefined); + }).catch((e: BusinessError): void => { + callback(e, undefined); + }); +} + +function symlinkSync(target: string, srcPath: string): void { + return FileIoImpl.symlinkSync(target, srcPath); +} + +function symlink(target: string, srcPath: string): Promise { + return new Promise((resolve: (result: undefined) => void, + reject: (e: BusinessError) => void): void => { + let promise = taskpool.execute((target: string, srcPath: string): undefined => { + return FileIoImpl.symlinkSync(target, srcPath); + }, target, srcPath); + promise.then((ret: NullishType): void => { + resolve(undefined); + }).catch((e: BusinessError): void => { + reject(e); + }); + }); +} +function renameSync(oldPath: string, newPath: string): void { + return FileIoImpl.renameSync(oldPath, newPath); +} + +function rename(oldPath: string, newPath: string): Promise { + return new Promise((resolve: (result: undefined) => void, reject: (e: BusinessError) => void): void => { + let promise = taskpool.execute((oldPath: string, newPath: string): undefined => { + return FileIoImpl.renameSync(oldPath, newPath); + }, oldPath, newPath); + promise.then((ret: NullishType): void => { + resolve(undefined); + }).catch((e: BusinessError): void => { + reject(e); + }); + }); +} + +function rename(oldPath: string, newPath: string, callback: AsyncCallback): void { + let promise = taskpool.execute((oldPath: string, newPath: string): undefined => { + return FileIoImpl.renameSync(oldPath, newPath); + }, oldPath, newPath); + promise.then((ret: NullishType): void => { + let e = new BusinessError(); + e.code = 0; + callback(e, undefined); + }).catch((e: BusinessError): void => { + callback(e, undefined); + }); +} + +function createRandomAccessFileSync(file: string | File, mode?: number, + options?: RandomAccessFileOptions): RandomAccessFile { + return FileIoImpl.createRandomAccessFileSync(file, mode, options); +} + +function createRandomAccessFile(file: string | File, mode?: number, + options?: RandomAccessFileOptions): Promise { + return new Promise((resolve: (result: RandomAccessFile) => void, + reject: (e: BusinessError) => void) => { + let promise = taskpool.execute((file: string | File, mode?: number, + options?: RandomAccessFileOptions): RandomAccessFile => { + return FileIoImpl.createRandomAccessFileSync(file, mode, options); + }, file, mode, options); + promise.then((ret: NullishType): void => { + let raffile = ret as RandomAccessFileInner; + resolve(raffile); + }).catch((e: BusinessError): void => { + reject(e); + }); + }); +} + +function fdopenStream(fd: number, mode: string): Promise { + return new Promise((resolve: (result: Stream) => void, reject: (e: BusinessError) => void) => { + let promise = taskpool.execute((fd: number, mode: string): Stream => { + return FileIoImpl.fdopenStreamSync(fd, mode); + }, fd, mode); + promise.then((ret: NullishType): void => { + let stream = ret as Stream; + resolve(stream); + }).catch((e: BusinessError): void => { + reject(e); + }); + }); +} + +function setxattrSync(path: string, key: string, value: string): void { + return FileIoImpl.setxattrSync(path, key, value) +} + +function setxattr(path: string, key: string, value: string): Promise { + return new Promise((resolve: (result: undefined) => void, reject: (e: BusinessError) => void): void => { + let promise = taskpool.execute((path: string, key: string, value: string): undefined => + FileIoImpl.setxattrSync(path, key, value), path, key, value); + promise.then((ret: NullishType): void => { + resolve(undefined); + }).catch((e: BusinessError): void => { + reject(e as BusinessError); + }); + }); +} + +function createRandomAccessFile(file: string | File, callback: AsyncCallback): void { + let promise = taskpool.execute((file: string | File): RandomAccessFile => { + return FileIoImpl.createRandomAccessFileSync(file); + }, file); + promise.then((ret: NullishType): void => { + let e = new BusinessError(); + e.code = 0; + let raffile = ret as RandomAccessFile; + callback(e, raffile); + }).catch((e: BusinessError): void => { + let f: RandomAccessFile = new RandomAccessFileInner(0); + callback(e, f); + }); +} + +function createRandomAccessFile(file: string | File, mode: number, + callback: AsyncCallback): void { + let promise = taskpool.execute((file: string | File, mode: number): RandomAccessFile => { + return FileIoImpl.createRandomAccessFileSync(file, mode); + }, file, mode); + promise.then((ret: NullishType): void => { + let e = new BusinessError(); + e.code = 0; + let raffile = ret as RandomAccessFile; + callback(e, raffile); + }).catch((e: BusinessError): void => { + let f: RandomAccessFile = new RandomAccessFileInner(0); + callback(e, f); + }); +} + +function fdopenStream(fd: number, mode: string, callback: AsyncCallback): void { + let promise = taskpool.execute((fd: number, mode: string): Stream => { + return FileIoImpl.fdopenStreamSync(fd, mode); + }, fd, mode); + promise.then((ret: NullishType): void => { + let e = new BusinessError(); + e.code = 0; + let stream = ret as Stream; + callback(e, stream); + }).catch((e: BusinessError): void => { + let r: Stream = new StreamInner(0); + callback(e, r); + }); +} + +function fdopenStreamSync(fd: number, mode: string): Stream { + return FileIoImpl.fdopenStreamSync(fd, mode); +} + +function createStream(path: string, mode: string): Promise { + return new Promise((resolve: (result: Stream) => void, reject: (e: BusinessError) => void) => { + let promise = taskpool.execute((path: string, mode: string): Stream => { + return FileIoImpl.createStreamSync(path, mode); + }, path, mode); + promise.then((ret: NullishType): void => { + let stream = ret as Stream; + resolve(stream); + }).catch((e: BusinessError): void => { + reject(e); + }); + }); +} + +function createStream(path: string, mode: string, callback: AsyncCallback): void { + let promise = taskpool.execute((path: string, mode: string): Stream => { + return FileIoImpl.createStreamSync(path, mode); + }, path, mode); + promise.then((ret: NullishType): void => { + let e = new BusinessError(); + e.code = 0; + let stream = ret as Stream; + callback(e, stream); + }).catch((e: BusinessError): void => { + let r: Stream = new StreamInner(0); + callback(e, r); + }); +} + +function createStreamSync(path: string, mode: string): Stream { + return FileIoImpl.createStreamSync(path, mode); +} + +// function createReadStream(path: string, options?: ReadStreamOptions): ReadStream { +// return new ReadStream(path, options) +// } + +// function createWriteStream(path: string, options?: WriteStreamOptions): WriteStream { +// return new WriteStream(path, options); +// } + +function createWatcher(path: string, events: number, listener: WatchEventListener): Watcher { + return FileIoImpl.createWatcherSync(path, events, listener); +} + +function symlink(target: string, srcPath: string, callback: AsyncCallback): void { + let promise = taskpool.execute((target: string, srcPath: string): undefined => { + return FileIoImpl.symlinkSync(target, srcPath); + }, target, srcPath); + promise.then((ret: NullishType): void => { + let e = new BusinessError(); + e.code = 0; + callback(e, undefined); + }).catch((e: BusinessError): void => { + callback(e, undefined); + }); +} + +function utimes(path: string, mtime: number): void { + return FileIoImpl.utimes(path, mtime); +} + +function lstatSync(path: string): Stat { + return FileIoImpl.lstatSync(path) +} + +function lstat(path: string): Promise { + return new Promise((resolve: (result: Stat) => void, reject: (e: BusinessError) => void) => { + let promise = taskpool.execute((path: string): Stat => { + return FileIoImpl.lstatSync(path); + }, path); + promise.then((ret: NullishType): void => { + if (ret === null || ret === undefined) { + let e = new BusinessError(); + e.code = -1; + reject(e); + } else { + let r = ret as Stat; + resolve(r); + } + }).catch((e: BusinessError): void => { + reject(e); + }); + }); +} + +function lstat(path: string, callback: AsyncCallback): void { + let p = taskpool.execute((path: string): Stat => { + return FileIoImpl.lstatSync(path); + }, path); + p.then((ret: NullishType): void => { + let e = new BusinessError(); + if (ret === null || ret === undefined) { + e.code = -1; + let stat: Stat = new StatInner(0); + callback(e, stat); + } else { + e.code = 0; + let r = ret as Stat; + callback(e, r); + } + }).catch((e: BusinessError): void => { + callback(e, new StatInner(0)); + }); +} +function copyFile(src: string | number, dest: string | number, mode?: number): Promise { + return new Promise((resolve: (result: undefined) => void, reject: (e: BusinessError) => void): void => { + let promise = taskpool.execute((src: string | number, dest: string | number, mode?: number): undefined => + FileIoImpl.copyFileSync(src, dest, mode), src, dest, mode); + promise.then((ret: NullishType): void => { + resolve(undefined); + }).catch((e: BusinessError): void => { + reject(e); + }); + }); +} + +function copy(srcUri: string, destUri: string, options?: CopyOptions): Promise { + return new Promise((resolve: (result: undefined) => void, reject: (e: BusinessError) => void): void => { + let promise = taskpool.execute((srcUri: string, destUri: string, options?: CopyOptions): undefined => + FileIoImpl.copySync(srcUri, destUri, options), srcUri, destUri, options); + promise.then((ret: NullishType): void => { + resolve(undefined); + }).catch((e: BusinessError): void => { + reject(e); + }); + }); +} + +function copyFile(src: string | number, dest: string | number, mode: number, callback: AsyncCallback): void { + let promise = taskpool.execute((src: string | number, dest: string | number, mode: number): undefined => + FileIoImpl.copyFileSync(src, dest, mode), src, dest, mode); + promise.then((ret: NullishType): void => { + let e = new BusinessError(); + e.code = 0; + callback(e, undefined); + }).catch((e: BusinessError): void => { + callback(e, undefined); + }); +} + +function copy(srcUri: string, destUri: string, options: CopyOptions, callback: AsyncCallback): void { + let promise = taskpool.execute((srcUri: string, destUri: string, options: CopyOptions): undefined => + FileIoImpl.copySync(srcUri, destUri, options), srcUri, destUri, options); + promise.then((ret: NullishType): void => { + let e = new BusinessError(); + e.code = 0; + callback(e, undefined); + }).catch((e: BusinessError): void => { + callback(e, undefined); + }); +} + +function copyFile(src: string | number, dest: string | number, callback: AsyncCallback): void { + let promise = taskpool.execute((src: string | number, dest: string | number): undefined => + FileIoImpl.copyFileSync(src, dest), src, dest); + promise.then((ret: NullishType): void => { + let e = new BusinessError(); + e.code = 0; + callback(e, undefined); + }).catch((e: BusinessError): void => { + callback(e, undefined); + }); +} + +function copy(srcUri: string, destUri: string, callback: AsyncCallback): void { + let promise = taskpool.execute((srcUri: string, destUri: string): undefined => + FileIoImpl.copySync(srcUri, destUri), srcUri, destUri); + promise.then((ret: NullishType): void => { + let e = new BusinessError(); + e.code = 0; + callback(e, undefined); + }).catch((e: BusinessError): void => { + callback(e, undefined); + }); +} + +function lseek(fd: number, offset: number, whence?: WhenceType): number { + return FileIoImpl.lseekSync(fd, offset, whence); +} + +export interface Filter { + suffix?: Array; + displayName?: Array; + mimeType?: Array; + fileSizeOver?: number; + lastModifiedAfter?: number; + excludeMedia?: boolean; +} + +export interface Progress { + processedSize: number; + totalSize: number; +} + +export interface DfsListeners { + onStatus(networkId: string, status: number): void; +} + +export class ProgressInner implements Progress { + processedSize: number; + totalSize: number; + + constructor(pSize: number, tSize: number) { + this.processedSize = pSize; + this.totalSize = tSize; + } +} + +export type ProgressListener = (progress: Progress) => void; + +export class TaskSignal { + private nativeTaskSignal: long = 0; + private native onCancelNative(): void; + private onCancelResolve: (path: string) => void = (path: string): void => {}; + private onCancelCallback(path: string): void { + if (this.onCancelResolve) { + this.onCancelResolve(path); + } + } + native cancel(): void; + onCancel(): Promise { + return new Promise((resolve: (path: string) => void, reject: (e: BusinessError) => void): void => { + this.onCancelResolve = resolve; + this.onCancelNative(); + }); + } +} + +export interface CopyOptions { + progressListener?: ProgressListener; + copySignal?: TaskSignal; +} + +export enum AccessModeType { + EXIST = 0, + WRITE = 2, + READ = 4, + READ_WRITE = 6, +} + +export enum AccessFlagType { + LOCAL = 0, +} + +export interface RandomAccessFile { + fd: number; + filePointer: number; + + setFilePointer(filePointer: number): void; + close(): void; + write(buffer: ArrayBuffer | string, options?: WriteOptions): Promise; + write(buffer: ArrayBuffer | string, callback: AsyncCallback): void; + write(buffer: ArrayBuffer | string, options: WriteOptions, callback: AsyncCallback): void; + writeSync(buffer: ArrayBuffer | string, options?: WriteOptions): number; + read(buffer: ArrayBuffer, options?: ReadOptions): Promise; + read(buffer: ArrayBuffer, callback: AsyncCallback): void; + read(buffer: ArrayBuffer, options: ReadOptions, callback: AsyncCallback): void; + readSync(buffer: ArrayBuffer, options?: ReadOptions): number; + // getReadStream(): ReadStream; + // getWriteStream(): WriteStream; +} + +export class RandomAccessFileInner implements RandomAccessFile { + fd: number = -1; + filePointer: number = -1; + + private nativePtr: long = 0; + + constructor(ptr: long) { + if (this.nativePtr === 0) { + this.nativePtr = ptr; + } + } + + setFilePointer(filePointer: number): void { + this.setFilePointer0(filePointer); + this.filePointer = filePointer; + } + + native setFilePointer0(filePointer: number): void; + + native close(): void; + + writeSync(buffer: ArrayBuffer | string, options?: WriteOptions): number { + let length = options ? this.writeSync0(buffer, options) : this.writeSync0(buffer); + this.filePointer += (options?.offset?? 0) + length; + return length; + } + + native writeSync0(buffer: ArrayBuffer | string, options?: WriteOptions): number; + + write(buffer: ArrayBuffer | string, options?: WriteOptions): Promise { + return new Promise((resolve: (result: number) => void, reject: (e: BusinessError) => void) => { + let promise = taskpool.execute((buffer: ArrayBuffer | string, options?: WriteOptions): number => { + return this.writeSync(buffer, options); + }, buffer, options); + promise.then((ret: NullishType): void => { + let result = ret as number + resolve(result); + }).catch((e: BusinessError): void => { + reject(e); + }); + }); + } + + write(buffer: ArrayBuffer | string, options: WriteOptions, callback: AsyncCallback): void { + let promise = taskpool.execute((buffer: ArrayBuffer | string, options: WriteOptions): number => { + return this.writeSync(buffer, options); + }, buffer, options); + promise.then((ret: NullishType): void => { + let e = new BusinessError(); + e.code = 0; + let result = ret as number; + callback(e, result); + }).catch((e: BusinessError): void => { + callback(e, 0); + }); + } + + write(buffer: ArrayBuffer | string, callback: AsyncCallback): void { + let promise = taskpool.execute((buffer: ArrayBuffer | string): number => { + return this.writeSync(buffer); + }, buffer); + promise.then((ret: NullishType): void => { + let e = new BusinessError(); + e.code = 0; + let result = ret as number; + callback(e, result); + }).catch((e: BusinessError): void => { + callback(e, 0); + }); + } + + readSync(buffer: ArrayBuffer, options?: ReadOptions): number { + const length = options ? this.readSync0(buffer, options) : this.readSync0(buffer); + this.filePointer += (options?.offset?? 0) + length; + return length; + } + + native readSync0(buffer: ArrayBuffer, options?: ReadOptions): number; + + read(buffer: ArrayBuffer, options?: ReadOptions): Promise { + return new Promise((resolve: (result: number) => void, reject: (e: BusinessError) => void) => { + let promise = taskpool.execute((buffer: ArrayBuffer, options?: ReadOptions): number => { + return this.readSync(buffer, options); + }, buffer, options); + promise.then((ret: NullishType): void => { + let result = ret as number; + resolve(result); + }).catch((e: BusinessError): void => { + reject(e); + }); + }); + } + + read(buffer: ArrayBuffer, options: ReadOptions, callback: AsyncCallback): void { + let promise = taskpool.execute((buffer: ArrayBuffer, options: ReadOptions): number => { + return this.readSync(buffer, options); + }, buffer, options); + promise.then((ret: NullishType): void => { + let e = new BusinessError(); + e.code = 0; + let result = ret as number; + callback(e, result); + }).catch((e: BusinessError): void => { + callback(e, 0); + }); + } + + read(buffer: ArrayBuffer, callback: AsyncCallback): void { + let promise = taskpool.execute((buffer: ArrayBuffer): number => { + return this.readSync(buffer); + }, buffer); + promise.then((ret: NullishType): void => { + let e = new BusinessError(); + e.code = 0; + let result = ret as number; + callback(e, result); + }).catch((e: BusinessError): void => { + callback(e, 0); + }); + } + + // native getReadStream(): ReadStream; + // native getWriteStream(): WriteStream; +} + +export interface File { + fd: number; + path: String; + name: String; + + getParent(): String; + lock(exclusive?: boolean): Promise; + lock(callback: AsyncCallback): void; + lock(exclusive: boolean, callback: AsyncCallback): void; + tryLock(exclusive?: boolean): void; + unlock(): void; +} + +export class FileInner implements File { + fd: number = -1; + path: String = ""; + name: String = ""; + + private nativePtr: long = 0; + + constructor(ptr: long) { + if (this.nativePtr === 0) { + this.nativePtr = ptr; + } + } + + native getParent(): String; + native lockSync(exclusive?: boolean): void; + + lock(exclusive?: boolean): Promise { + return new Promise((resolve: (result: undefined) => void, reject: (e: BusinessError) => void): void => { + let promise = taskpool.execute((exclusive?: boolean): undefined => { + return this.lockSync(exclusive); + }, exclusive); + promise.then((ret: NullishType): void => { + resolve(undefined); + }).catch((e: BusinessError): void => { + reject(e); + }); + }); + } + + lock(callback: AsyncCallback): void { + let promise = taskpool.execute((): undefined => { + return this.lockSync(); + }); + promise.then((ret: NullishType): void => { + let e = new BusinessError(); + e.code = 0; + callback(e, undefined); + }).catch((e: BusinessError): void => { + callback(e, undefined); + }); + } + + lock(exclusive: boolean, callback: AsyncCallback): void { + let promise = taskpool.execute((exclusive: boolean): undefined => { + return this.lockSync(exclusive); + }, exclusive); + promise.then((ret: NullishType): void => { + let e = new BusinessError(); + e.code = 0; + callback(e, undefined); + }).catch((e: BusinessError): void => { + callback(e, undefined); + }); + } + + native tryLock(exclusive?: boolean): void; + native unlock(): void; + +} + +export enum LocationType { + LOCAL = 1, + CLOUD = 2 +} + + +export class ReaderIteratorResultInner implements ReaderIteratorResult { + private nativePtr: long = 0; + + constructor(ptr: long) { + if (this.nativePtr === 0) { + this.nativePtr = ptr; + } + } + + done: boolean = false; + value: string = ""; +} + +export interface ReaderIterator { + next(): ReaderIteratorResult; +} + +export class ReaderIteratorInner implements ReaderIterator { + private nativePtr: long = 0; + + constructor(ptr: long) { + if (this.nativePtr === 0) { + this.nativePtr = ptr; + } + } + + native next(): ReaderIteratorResult; +} + +export interface Stat { + ino: bigint; + mode: number; + uid: number; + gid: number; + size: number; + atime: number; + mtime: number; + ctime: number; + atimeNs: bigint; + mtimeNs: bigint; + ctimeNs: bigint; + location: LocationType; + + isBlockDevice(): boolean; + isCharacterDevice(): boolean; + isDirectory(): boolean; + isFIFO(): boolean; + isFile(): boolean; + isSocket(): boolean; + isSymbolicLink(): boolean; +} + +export class StatInner implements Stat { + ino: bigint = 0n; + mode: number; + uid: number; + gid: number; + size: number; + atime: number; + mtime: number; + ctime: number; + atimeNs: bigint = 0n; + mtimeNs: bigint = 0n; + ctimeNs: bigint = 0n; + location: LocationType = LocationType.LOCAL; + + private nativeStat: long = 0; + + constructor(stat: long) { + if (this.nativeStat === 0) { + this.nativeStat = stat; + } + } + + native isBlockDevice(): boolean; + native isCharacterDevice(): boolean; + native isDirectory(): boolean; + native isFIFO(): boolean; + native isFile(): boolean; + native isSocket(): boolean; + native isSymbolicLink(): boolean; +} + +export interface Stream { + close(): Promise; + close(callback: AsyncCallback): void; + closeSync(): void; + flush(): Promise; + flush(callback: AsyncCallback): void; + flushSync(): void; + write(buffer: ArrayBuffer | string, options?: WriteOptions): Promise; + write(buffer: ArrayBuffer | string, callback: AsyncCallback): void; + write(buffer: ArrayBuffer | string, options: WriteOptions, callback: AsyncCallback): void; + writeSync(buffer: ArrayBuffer | string, options?: WriteOptions): number; + read(buffer: ArrayBuffer, options?: ReadOptions): Promise; + read(buffer: ArrayBuffer, callback: AsyncCallback): void; + read(buffer: ArrayBuffer, options: ReadOptions, callback: AsyncCallback): void; + readSync(buffer: ArrayBuffer, options?: ReadOptions): number; + seek(offset: number, whence?: number): number; +} + +export class StreamInner implements Stream { + private nativePtr: long = 0; + + constructor(ptr: long) { + if (this.nativePtr === 0) { + this.nativePtr = ptr; + } + } + + close(): Promise { + return new Promise((resolve: (result: undefined) => void, reject: (e: BusinessError) => void): void => { + let promise = taskpool.execute((): undefined => this.closeSync()); + promise.then((ret: NullishType): void => { + resolve(undefined); + }).catch((e: BusinessError): void => { + reject(e); + }); + }); + } + + close(callback: AsyncCallback): void { + let promise = taskpool.execute((): undefined => this.closeSync()); + promise.then((ret: NullishType): void => { + let e = new BusinessError(); + e.code = 0; + callback(e, undefined); + }).catch((e: BusinessError): void => { + callback(e, undefined); + }); + } + + native closeSync(): void; + + flush(): Promise { + return new Promise((resolve: (result: undefined) => void, reject: (e: BusinessError) => void): void => { + let promise = taskpool.execute((): undefined => this.flushSync()); + promise.then((ret: NullishType): void => { + resolve(undefined); + }).catch((e: BusinessError): void => { + reject(e); + }); + }); + } + + flush(callback: AsyncCallback): void { + let promise = taskpool.execute((): undefined => this.flushSync()); + promise.then((ret: NullishType): void => { + let e = new BusinessError(); + e.code = 0; + callback(e, undefined); + }).catch((e: BusinessError): void => { + callback(e, undefined); + }); + } + + native flushSync(): void; + + write(buffer: ArrayBuffer | string, options?: WriteOptions): Promise { + return new Promise((resolve: (result: number) => void, reject: (e: BusinessError) => void) => { + let promise = taskpool.execute((buffer: ArrayBuffer | string, options?: WriteOptions): number => { + return this.writeSync(buffer, options); + }, buffer, options); + promise.then((ret: NullishType): void => { + let result = ret as number + resolve(result); + }).catch((e: BusinessError): void => { + reject(e); + }); + }); + } + + write(buffer: ArrayBuffer | string, callback: AsyncCallback): void { + let promise = taskpool.execute((buffer: ArrayBuffer | string): number => { + return this.writeSync(buffer); + }, buffer); + promise.then((ret: NullishType): void => { + let e = new BusinessError(); + e.code = 0; + let result = ret as number; + callback(e, result); + }).catch((e: BusinessError): void => { + callback(e, 0); + }); + } + + write(buffer: ArrayBuffer | string, options: WriteOptions, callback: AsyncCallback): void { + let promise = taskpool.execute((buffer: ArrayBuffer | string, options: WriteOptions): number => { + return this.writeSync(buffer, options); + }, buffer, options); + promise.then((ret: NullishType): void => { + let e = new BusinessError(); + e.code = 0; + let result = ret as number; + callback(e, result); + }).catch((e: BusinessError): void => { + callback(e, 0); + }); + } + + native writeSync(buffer: ArrayBuffer | string, options?: WriteOptions): number; + + read(buffer: ArrayBuffer, options?: ReadOptions): Promise { + return new Promise((resolve: (result: number) => void, reject: (e: BusinessError) => void) => { + let promise = taskpool.execute((buffer: ArrayBuffer, options?: ReadOptions): number => { + return this.readSync(buffer, options); + }, buffer, options); + promise.then((ret: NullishType): void => { + let result = ret as number + resolve(result); + }).catch((e: BusinessError): void => { + reject(e); + }); + }); + } + + read(buffer: ArrayBuffer, callback: AsyncCallback): void { + let promise = taskpool.execute((buffer: ArrayBuffer): number => { + return this.readSync(buffer); + }, buffer); + promise.then((ret: NullishType): void => { + let e = new BusinessError(); + e.code = 0; + let result = ret as number; + callback(e, result); + }).catch((e: BusinessError): void => { + callback(e, 0); + }); + } + + read(buffer: ArrayBuffer, options: ReadOptions, callback: AsyncCallback): void { + let promise = taskpool.execute((buffer: ArrayBuffer, options: ReadOptions): number => { + return this.readSync(buffer, options); + }, buffer, options); + promise.then((ret: NullishType): void => { + let e = new BusinessError(); + e.code = 0; + let result = ret as number; + callback(e, result); + }).catch((e: BusinessError): void => { + callback(e, 0); + }); + } + + native readSync(buffer: ArrayBuffer, options?: ReadOptions): number; + native seek(offset: number, whence?: number): number; +} + +// export class ReadStream extends stream.Readable { +// path: string; +// bytesRead: number; +// private offset: number; +// private start?: number; +// private end?: number; +// private stream?: Stream; + +// constructor(path: string, options?: ReadStreamOptions) { +// super(); +// this.path = path; +// this.bytesRead = 0; +// this.start = options?.start; +// this.end = options?.end; +// this.stream = createStreamSync(this.path, 'r'); +// this.offset = this.start ?? 0; +// } + +// seek(offset: number, whence?: WhenceType): number { +// if (whence === undefined) { +// let off = this.stream?.seek(offset); +// if (off !== undefined) { +// this.offset = off +// } +// } else { +// let off = this.stream?.seek(offset, whence); +// if (off !== undefined) { +// this.offset = off +// } +// } +// return this.offset; +// } + +// close(): void { +// this.stream?.close(); +// } + +// doInitialize(callback: () => void): void { +// callback(); +// } + +// doRead(size: number): void { +// let readSize = size; +// let end = this.end +// if (end !== undefined) { +// if (this.offset > end) { +// this.push(null); +// return; +// } +// if (this.offset + readSize > end) { +// readSize = end - this.offset; +// } +// } +// let buffer = new ArrayBuffer(readSize); +// const off = this.offset; +// this.offset += readSize; +// this.stream?.read(buffer, { offset: off, length: readSize }) +// .then((readOut: number) => { +// if (readOut > 0) { +// this.bytesRead += readOut; +// this.push(new Uint8Array(buffer.slice(0, readOut))); +// } +// if (readOut !== readSize || readOut < size) { +// this.offset = this.offset - readSize + readOut; +// this.push(null); +// } +// }); +// } +// } + +// export class WriteStream extends stream.Writable { +// path: string; +// bytesWritten: number; +// private offset: number; +// private mode: string; +// private start?: number; +// private stream?: Stream; + +// constructor(path: string, options?: WriteStreamOptions) { +// super(); +// this.path = path; +// this.bytesWritten = 0; +// this.start = options?.start; +// this.mode = this.convertOpenMode(options?.mode); +// this.stream = createStreamSync(this.path, this.mode); +// this.offset = this.start ?? 0; +// } + +// seek(offset: number, whence?: WhenceType): number { +// if (whence === undefined) { +// let off = this.stream?.seek(offset); +// if (off !== undefined) { +// this.offset = off +// } +// } else { +// let off = this.stream?.seek(offset, whence); +// if (off !== undefined) { +// this.offset = off +// } +// } +// return this.offset; +// } + +// close(): void { +// this.stream?.close(); +// } + +// closeSync(): void { +// this.stream?.closeSync(); +// } + +// doInitialize(callback: () => void): void { +// callback(); +// } + +// doWrite(chunk: string | ArrayBuffer, encoding: string, callback: () => void): void { +// this.stream?.write(chunk, { offset: this.offset }) +// .then((writeIn: number) => { +// this.offset += writeIn; +// this.bytesWritten += writeIn; +// callback(); +// }) +// .finally(() => { +// this.stream?.flush(); +// }); +// } + +// convertOpenMode(mode?: number): string { +// let modeStr = 'w'; +// if (mode === undefined) { +// return modeStr; +// } +// if ((mode as number) & fileIo.OpenMode.WRITE_ONLY) { +// modeStr = 'w'; +// } +// if ((mode as number) & fileIo.OpenMode.READ_WRITE) { +// modeStr = 'w+'; +// } +// if (((mode as number) & fileIo.OpenMode.WRITE_ONLY) && ((mode as number) & fileIo.OpenMode.APPEND)) { +// modeStr = 'a'; +// } +// if (((mode as number) & fileIo.OpenMode.READ_WRITE) && ((mode as number) & fileIo.OpenMode.APPEND)) { +// modeStr = 'a+'; +// } +// return modeStr; +// } +// } + +export class AtomicFile { + static { + loadLibrary("ani_file_fs"); + } + + private nativePtr: long = 0; + private native getPath(): string; + // private writeStream: WriteStream | null = null; + + native constructor(path: string); + + native getBaseFile(): File; + + // native openRead(): ReadStream; + + native readFully(): ArrayBuffer; + + // native nativeStartWrite(): WriteStream; + // startWrite(): WriteStream { + // let ws = this.nativeStartWrite(); + // this.writeStream = ws; + // return ws; + // } + + // native nativeFinishWrite(): void; + // finishWrite(): void { + // if (!this.writeStream) { + // throw createBusinessError(UNKNOWN_ERR, UNKNOWN_MSG); + // } + // this.writeStream?.close(); + // this.nativeFinishWrite(); + // this.writeStream = null; + // }; + + // native nativeFailWrite(): void; + // failWrite(): void { + // if (!this.writeStream) { + // throw createBusinessError(UNKNOWN_ERR, UNKNOWN_MSG); + // } + // this.writeStream?.close(); + // this.nativeFailWrite(); + // this.writeStream = null; + // }; + + native delete(): void; +} + +export enum WhenceType { + SEEK_SET = 0, + SEEK_CUR = 1, + SEEK_END = 2 +} + +export interface Watcher { + start(): void; + stop(): void; +} + +class WatcherInner implements Watcher { + private nativePtr: long = 0; + + constructor(ptr: long) { + if (this.nativePtr === 0) { + this.nativePtr = ptr; + } + } + + native start(): void; + + native stop(): void; +} + +} // namespace fileIo + +export interface ConflictFiles { + srcFile: string; + destFile: string; +} + +class ConflictFilesInner implements ConflictFiles { + srcFile: string = ""; + destFile: string = ""; + + constructor(src: string, dest: string) { + this.srcFile = src; + this.destFile = dest; + } +} + +export interface WatchEvent { + fileName: string; + event: number; + cookie: number; +} + +class WatchEventInner implements WatchEvent { + fileName: string = ''; + event: number; + cookie: number; + + constructor(fileName: string, event: number, cookie: number) { + this.fileName = fileName; + this.event = event; + this.cookie = cookie; + } + +} + +export type WatchEventListener = (event: WatchEvent) => void; + +export interface Options { + encoding?: string; +} + +export interface ReadOptions { + offset?: number; + length?: number; +} + +export interface ReadTextOptions extends ReadOptions { + encoding?: string; +} + +export interface WriteOptions extends Options { + offset?: number; + length?: number; +} + +export interface RandomAccessFileOptions { + start?: number; + end?: number; +} + +export interface ListFileOptions { + recursion?: boolean; + listNum?: number; + filter?: Filter; +} + +export interface WriteStreamOptions { + mode?: number; + start?: number; +} + +export interface ReadStreamOptions { + start?: number; + end?: number; +} + +export class ReadStreamOptionsInner implements ReadStreamOptions { + constructor() {} + start?: number; + end?: number; +} + +export class WriteStreamOptionsInner implements WriteStreamOptions { + constructor() {} + mode?: number; + start?: number; +} + +export interface ReaderIteratorResult { + done: boolean; + value: string; +} + +export interface Filter { + suffix?: Array; + displayName?: Array; + mimeType?: Array; + fileSizeOver?: number; + lastModifiedAfter?: number; + excludeMedia?: boolean; +} + +type TaskSignal = fileIo.TaskSignal; +type DfsListeners = fileIo.DfsListeners; + + +export class FileIoImpl { + + static { + loadLibrary("ani_file_fs"); + } + + static native doAccessSync(path: string, mode?: fileIo.AccessModeType, flag?: fileIo.AccessFlagType): boolean; + + static native closeSync(file: number | fileIo.File): void; + + static native copySync(srcUri: string, destUri: string, options?: fileIo.CopyOptions): void; + + static native connectDfs(networkId: string, listeners: DfsListeners): void; + + static native copyDirSync(src: string, dest: string, mode?: number): void; + + static native copyFileSync(src: string | number, dest: string | number, mode?: number): void; + + static native disConnectDfs(networkId: string): void; + + static native fdatasyncSync(fd: number): void; + + static native getxattrSync(path: string, key: string): string; + + static native createStreamSync(path: string, mode: string): fileIo.Stream; + + static native createWatcherSync(path: string, events: number, listener: WatchEventListener): fileIo.Watcher; + + static native fdopenStreamSync(fd: number, mode: string): fileIo.Stream; + + static native dup(fd: number): fileIo.File; + + static native listFileSync(path: string, options?: ListFileOptions): string[]; + + static native lstatSync(path: string): fileIo.Stat; + + static native lseekSync(fd: number, offset: number, whence?: fileIo.WhenceType): number; + + static native mkdirSync(path: string): void; + + static native mkdirSync(path: string, recursion: boolean): void; + + static native movedirSync(src: string, dest: string, mode?: number): void; + + static native mkdtempSync(prefix: string): string; + + static native moveFileSync(src: String, dest: String, mode?: number): void; + + static native openSync(path: String, mode?: number): fileIo.File; + + static native readlinesSync(filePath: string, options?: Options): fileIo.ReaderIterator; + + static native readSync(fd: number, buffer: ArrayBuffer, options?: ReadOptions): number; + + static native readTextSync(filePath: string, options?: ReadTextOptions): string; + + static native rmdirSync(path: string): void; + + static native setxattrSync(path: string, key: string, value: string): void; + + static native statSync(file: string | number): fileIo.Stat; + + static native truncateSync(file: string | number, len?: number): void; + + static native unlinkSync(path: string): void; + + static native writeSync(fd: number, buffer: string | ArrayBuffer, options?: WriteOptions): number; + + static native fsyncSync(fd: number): void; + + static native renameSync(oldPath: string, newPath: string): void; + + static native createRandomAccessFileSync(file: string | fileIo.File, mode?: number, + options?: RandomAccessFileOptions): fileIo.RandomAccessFile; + + static native symlinkSync(target: string, srcPath: string): void; + + static native utimes(path: string, mtime: number): void; +} diff --git a/interfaces/kits/js/src/mod_fs/class_atomicfile/atomicfile_n_exporter.cpp b/interfaces/kits/js/src/mod_fs/class_atomicfile/atomicfile_n_exporter.cpp index 6958df62bed345e172ab6de31a4fac0e59f0c044..c814d7eacc0d120b30b3d948aac5fed834165e29 100644 --- a/interfaces/kits/js/src/mod_fs/class_atomicfile/atomicfile_n_exporter.cpp +++ b/interfaces/kits/js/src/mod_fs/class_atomicfile/atomicfile_n_exporter.cpp @@ -54,7 +54,7 @@ struct BufferData { static void FinalizeCallback(napi_env env, void *finalizeData, void *finalizeHint) { - BufferData *bufferData = static_cast(finalizeData); + BufferData *bufferData = static_cast(finalizeHint); delete bufferData; } @@ -388,7 +388,18 @@ napi_value AtomicFileNExporter::FinishWrite(napi_env env, napi_callback_info inf CallFunctionByName(env, writeStream, "closeSync"); - std::rename(rafEntity->newFileName.c_str(), rafEntity->baseFileName.c_str()); + int32_t result = std::rename(rafEntity->newFileName.c_str(), rafEntity->baseFileName.c_str()); + if (result != 0) { + HILOGE("Failed to rename file, ret:%{public}d", result); + status = napi_delete_reference(env, rafEntity->writeStreamObj); + if (status != napi_ok) { + HILOGE("Failed to delete reference"); + NError(UNKROWN_ERR).ThrowErr(env, "Failed to delete reference"); + return nullptr; + } + NError(UNKROWN_ERR).ThrowErr(env, "Failed to rename file"); + return nullptr; + } std::string tmpNewFileName = rafEntity->baseFileName; rafEntity->newFileName = tmpNewFileName.append(TEMP_FILE_SUFFIX); status = napi_delete_reference(env, rafEntity->writeStreamObj); @@ -424,6 +435,14 @@ napi_value AtomicFileNExporter::FailWrite(napi_env env, napi_callback_info info) if (!fs::remove(rafEntity->newFileName)) { HILOGW("Failed to remove file"); + status = napi_delete_reference(env, rafEntity->writeStreamObj); + if (status != napi_ok) { + HILOGE("Failed to delete reference"); + NError(UNKROWN_ERR).ThrowErr(env, "Failed to delete reference"); + return nullptr; + } + NError(UNKROWN_ERR).ThrowErr(env, "Failed to remove file"); + return nullptr; } std::string tmpNewFileName = rafEntity->baseFileName; rafEntity->newFileName = tmpNewFileName.append(TEMP_FILE_SUFFIX); diff --git a/interfaces/kits/js/src/mod_fs/class_file/ani/file_ani.cpp b/interfaces/kits/js/src/mod_fs/class_file/ani/file_ani.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f6353d3941544bf0258ee0bb5d2f5dbc02b2bbba --- /dev/null +++ b/interfaces/kits/js/src/mod_fs/class_file/ani/file_ani.cpp @@ -0,0 +1,121 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "file_ani.h" + +#include "error_handler.h" +#include "file_wrapper.h" +#include "filemgmt_libhilog.h" +#include "fs_file.h" +#include "type_converter.h" + +namespace OHOS { +namespace FileManagement { +namespace ModuleFileIO { +namespace ANI { +using namespace OHOS::FileManagement::ModuleFileIO; +using namespace std; + +ani_string FileAni::GetParent(ani_env *env, [[maybe_unused]] ani_object object) +{ + auto fsFile = FileWrapper::Unwrap(env, object); + if (fsFile == nullptr) { + HILOGE("Cannot unwrap fsfile!"); + ErrorHandler::Throw(env, UNKNOWN_ERR); + return {}; + } + auto ret = fsFile->GetParent(); + if (!ret.IsSuccess()) { + HILOGE("Cannot get file parent!"); + const auto &err = ret.GetError(); + ErrorHandler::Throw(env, err); + return {}; + } + auto value = ret.GetData().value(); + auto [succ, parent] = TypeConverter::ToAniString(env, value); + if (!succ) { + HILOGE("Cannot convert file parent to ani string!"); + ErrorHandler::Throw(env, UNKNOWN_ERR); + return {}; + } + return parent; +} + +void FileAni::LockSync(ani_env *env, [[maybe_unused]] ani_object object, ani_object exclusive) +{ + ani_boolean isUndefined; + bool exc = false; + env->Reference_IsUndefined(exclusive, &isUndefined); + if (!isUndefined) { + exc = true; + } + auto fsFile = FileWrapper::Unwrap(env, object); + if (fsFile == nullptr) { + HILOGE("Cannot unwrap fsfile!"); + ErrorHandler::Throw(env, UNKNOWN_ERR); + return; + } + auto ret = fsFile->Lock(exc); + if (!ret.IsSuccess()) { + HILOGE("Lock file failed!"); + const auto &err = ret.GetError(); + ErrorHandler::Throw(env, err); + return; + } +} + +void FileAni::TryLock(ani_env *env, [[maybe_unused]] ani_object object, ani_object exclusive) +{ + ani_boolean isUndefined; + bool exc = false; + env->Reference_IsUndefined(exclusive, &isUndefined); + if (!isUndefined) { + exc = true; + } + auto fsFile = FileWrapper::Unwrap(env, object); + if (fsFile == nullptr) { + HILOGE("Cannot unwrap fsfile!"); + ErrorHandler::Throw(env, UNKNOWN_ERR); + return; + } + auto ret = fsFile->TryLock(exc); + if (!ret.IsSuccess()) { + HILOGE("TryLock file failed!"); + const auto &err = ret.GetError(); + ErrorHandler::Throw(env, err); + return; + } +} + +void FileAni::UnLock(ani_env *env, [[maybe_unused]] ani_object object) +{ + auto fsFile = FileWrapper::Unwrap(env, object); + if (fsFile == nullptr) { + HILOGE("Cannot unwrap fsfile!"); + ErrorHandler::Throw(env, UNKNOWN_ERR); + return; + } + auto ret = fsFile->UnLock(); + if (!ret.IsSuccess()) { + HILOGE("UnLock file failed!"); + const auto &err = ret.GetError(); + ErrorHandler::Throw(env, err); + return; + } +} +} // namespace ANI +} // namespace ModuleFileIO +} // namespace FileManagement +} // namespace OHOS \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fs/class_file/ani/file_ani.h b/interfaces/kits/js/src/mod_fs/class_file/ani/file_ani.h new file mode 100644 index 0000000000000000000000000000000000000000..7a8e04c2c88a5149cb2f0a28252220d19b95b2e6 --- /dev/null +++ b/interfaces/kits/js/src/mod_fs/class_file/ani/file_ani.h @@ -0,0 +1,38 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef INTERFACES_KITS_JS_SRC_MOD_FS_CLASS_FILE_ANI_FILE_ANI_H +#define INTERFACES_KITS_JS_SRC_MOD_FS_CLASS_FILE_ANI_FILE_ANI_H + +#include + +namespace OHOS { +namespace FileManagement { +namespace ModuleFileIO { +namespace ANI { + +class FileAni final { +public: + static ani_string GetParent(ani_env *env, [[maybe_unused]] ani_object object); + static void LockSync(ani_env *env, [[maybe_unused]] ani_object object, ani_object exclusive); + static void TryLock(ani_env *env, [[maybe_unused]] ani_object object, ani_object exclusive); + static void UnLock(ani_env *env, [[maybe_unused]] ani_object object); +}; +} // namespace ANI +} // namespace ModuleFileIO +} // namespace FileManagement +} // namespace OHOS + +#endif // INTERFACES_KITS_JS_SRC_MOD_FS_CLASS_FILE_ANI_FILE_ANI_H \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fs/class_file/ani/file_wrapper.cpp b/interfaces/kits/js/src/mod_fs/class_file/ani/file_wrapper.cpp new file mode 100644 index 0000000000000000000000000000000000000000..fcbf8aab9ea4ca9007252a1e0feec0a6971502cc --- /dev/null +++ b/interfaces/kits/js/src/mod_fs/class_file/ani/file_wrapper.cpp @@ -0,0 +1,124 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "file_wrapper.h" + +#include "ani_signature.h" +#include "error_handler.h" +#include "filemgmt_libhilog.h" +#include "fs_file.h" +#include "type_converter.h" + +namespace OHOS { +namespace FileManagement { +namespace ModuleFileIO { +namespace ANI { +using namespace std; +using namespace OHOS::FileManagement::ModuleFileIO; +using namespace OHOS::FileManagement::ModuleFileIO::ANI::AniSignature; + +FsFile *FileWrapper::Unwrap(ani_env *env, ani_object object) +{ + ani_long nativePtr; + auto ret = env->Object_GetFieldByName_Long(object, "nativePtr", &nativePtr); + if (ret != ANI_OK) { + HILOGE("Unwrap fsFile err: %{private}d", ret); + return nullptr; + } + uintptr_t ptrValue = static_cast(nativePtr); + FsFile *file = reinterpret_cast(ptrValue); + return file; +} + +static bool SetFileProperties(ani_env *env, ani_class cls, ani_object obj, const FsFile *file) +{ + const auto &fdRet = file->GetFD(); + if (!fdRet.IsSuccess()) { + HILOGE("GetFD Failed!"); + return false; + } + + const auto &fd = fdRet.GetData().value(); + if (ANI_OK != AniHelper::SetPropertyValue(env, cls, obj, "fd", static_cast(fd))) { + HILOGE("Set fd field value failed!"); + return false; + } + + const auto &pathRet = file->GetPath(); + if (!pathRet.IsSuccess()) { + HILOGE("GetPath Failed!"); + return false; + } + + const auto &path = pathRet.GetData().value(); + if (ANI_OK != AniHelper::SetPropertyValue(env, cls, obj, "path", path)) { + HILOGE("Set path field value failed!"); + return false; + } + + const auto &nameRet = file->GetName(); + if (!pathRet.IsSuccess()) { + HILOGE("GetPath Failed!"); + return false; + } + + const auto &name = nameRet.GetData().value(); + if (ANI_OK != AniHelper::SetPropertyValue(env, cls, obj, "name", name)) { + HILOGE("Set name field value failed!"); + return false; + } + return true; +} + +ani_object FileWrapper::Wrap(ani_env *env, const FsFile *file) +{ + if (file == nullptr) { + HILOGE("FsFile pointer is null!"); + return nullptr; + } + + auto classDesc = FS::FileInner::classDesc.c_str(); + ani_class cls; + if (ANI_OK != env->FindClass(classDesc, &cls)) { + HILOGE("Cannot find class %s", classDesc); + return nullptr; + } + + auto ctorDesc = FS::FileInner::ctorDesc.c_str(); + auto ctorSig = FS::FileInner::ctorSig.c_str(); + ani_method ctor; + if (ANI_OK != env->Class_FindMethod(cls, ctorDesc, ctorSig, &ctor)) { + HILOGE("Cannot find constructor method for class %s", classDesc); + return nullptr; + } + + ani_long ptr = static_cast(reinterpret_cast(file)); + ani_object obj; + if (ANI_OK != env->Object_New(cls, ctor, &obj, ptr)) { + HILOGE("New %s obj Failed!", classDesc); + return nullptr; + } + + if (!SetFileProperties(env, cls, obj, file)) { + return nullptr; + } + + return obj; +} + +} // namespace ANI +} // namespace ModuleFileIO +} // namespace FileManagement +} // namespace OHOS \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fs/class_file/ani/file_wrapper.h b/interfaces/kits/js/src/mod_fs/class_file/ani/file_wrapper.h new file mode 100644 index 0000000000000000000000000000000000000000..2abf6113b7f7431d2e26feaa206f09758dd8cefb --- /dev/null +++ b/interfaces/kits/js/src/mod_fs/class_file/ani/file_wrapper.h @@ -0,0 +1,37 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef INTERFACES_KITS_JS_SRC_MOD_FS_CLASS_FILE_ANI_FILE_WRAPPER_H +#define INTERFACES_KITS_JS_SRC_MOD_FS_CLASS_FILE_ANI_FILE_WRAPPER_H + +#include +#include "fs_file.h" + +namespace OHOS { +namespace FileManagement { +namespace ModuleFileIO { +namespace ANI { + +class FileWrapper final { +public: + static FsFile *Unwrap(ani_env *env, ani_object object); + static ani_object Wrap(ani_env *env, const FsFile *file); +}; +} // namespace ANI +} // namespace ModuleFileIO +} // namespace FileManagement +} // namespace OHOS + +#endif // INTERFACES_KITS_JS_SRC_MOD_FS_CLASS_FILE_ANI_FILE_WRAPPER_H \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fs/class_file/file_instantiator.cpp b/interfaces/kits/js/src/mod_fs/class_file/file_instantiator.cpp new file mode 100644 index 0000000000000000000000000000000000000000..14080747ab3137c9e93cdd39c8f74f099a2b3d69 --- /dev/null +++ b/interfaces/kits/js/src/mod_fs/class_file/file_instantiator.cpp @@ -0,0 +1,83 @@ +/* +* Copyright (c) 2025 Huawei Device Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +#include "file_instantiator.h" + +#include "file_entity.h" +#include "file_utils.h" +#include "filemgmt_libhilog.h" + +namespace OHOS { +namespace FileManagement { +namespace ModuleFileIO { +using namespace std; +using namespace OHOS::DistributedFS; + +FsResult FileInstantiator::InstantiateFile(int fd, string pathOrUri, bool isUri) +{ + FsResult result = FsFile::Constructor(); + if (!result.IsSuccess()) { + HILOGE("Failed to instantiate class"); + int ret = close(fd); + if (ret < 0) { + HILOGE("Failed to close fd"); + } + return FsResult::Error(EIO); + } + + const FsFile *objFile = result.GetData().value(); + if (!objFile) { + HILOGE("Failed to get fsFile"); + int ret = close(fd); + if (ret < 0) { + HILOGE("Failed to close fd"); + } + return FsResult::Error(EIO); + } + + auto *fileEntity = objFile->GetFileEntity(); + if (!fileEntity) { + HILOGE("Failed to get fileEntity"); + int ret = close(fd); + if (ret < 0) { + HILOGE("Failed to close fd"); + } + delete objFile; + objFile = nullptr; + return FsResult::Error(EIO); + } + + auto fdg = CreateUniquePtr(fd, false); + if (fdg == nullptr) { + HILOGE("Failed to request heap memory."); + close(fd); + delete objFile; + objFile = nullptr; + return FsResult::Error(ENOMEM); + } + fileEntity->fd_.swap(fdg); + if (isUri) { + fileEntity->path_ = ""; + fileEntity->uri_ = pathOrUri; + } else { + fileEntity->path_ = pathOrUri; + fileEntity->uri_ = ""; + } + return result; +} + +} // namespace ModuleFileIO +} // namespace FileManagement +} // namespace OHOS \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fs/class_file/file_instantiator.h b/interfaces/kits/js/src/mod_fs/class_file/file_instantiator.h new file mode 100644 index 0000000000000000000000000000000000000000..12c73a57453e1c08ac1506a1fec148b095c35c9c --- /dev/null +++ b/interfaces/kits/js/src/mod_fs/class_file/file_instantiator.h @@ -0,0 +1,35 @@ +/* +* Copyright (c) 2025 Huawei Device Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +#ifndef INTERFACES_KITS_JS_SRC_MOD_FS_CLASS_FILE_FILE_INSTANTIATOR_H +#define INTERFACES_KITS_JS_SRC_MOD_FS_CLASS_FILE_FILE_INSTANTIATOR_H + +#include "filemgmt_libfs.h" +#include "fs_file.h" + +namespace OHOS { +namespace FileManagement { +namespace ModuleFileIO { +using namespace std; + +class FileInstantiator { +public: + static FsResult InstantiateFile(int fd, string pathOrUri, bool isUri); +}; + +} // namespace ModuleFileIO +} // namespace FileManagement +} // namespace OHOS +#endif // INTERFACES_KITS_JS_SRC_MOD_FS_CLASS_FILE_FILE_INSTANTIATOR_H \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fs/class_file/file_n_exporter.cpp b/interfaces/kits/js/src/mod_fs/class_file/file_n_exporter.cpp index f323319c16da6ad8ed770b2c438e05914d25b935..c6ef6778064fe3c226e6c376edc529d021f4cf63 100644 --- a/interfaces/kits/js/src/mod_fs/class_file/file_n_exporter.cpp +++ b/interfaces/kits/js/src/mod_fs/class_file/file_n_exporter.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022-2023 Huawei Device Co., Ltd. + * Copyright (c) 2022-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -13,20 +13,22 @@ * limitations under the License. */ -#include "file_entity.h" #include "file_n_exporter.h" #include #include #include #include -#include #include +#include + +#include "common_func.h" +#include "file_entity.h" #include "file_utils.h" #include "filemgmt_libhilog.h" #include "filemgmt_libn.h" -#include "../common_func.h" + #if !defined(WIN_PLATFORM) && !defined(IOS_PLATFORM) #include "file_uri.h" #endif diff --git a/interfaces/kits/js/src/mod_fs/class_file/fs_file.cpp b/interfaces/kits/js/src/mod_fs/class_file/fs_file.cpp new file mode 100644 index 0000000000000000000000000000000000000000..45cb2d418a482b26c9fb9475ce596d3716e1362f --- /dev/null +++ b/interfaces/kits/js/src/mod_fs/class_file/fs_file.cpp @@ -0,0 +1,202 @@ +/* +* Copyright (c) 2025 Huawei Device Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +#include "fs_file.h" + +#include + +#include "file_uri.h" +#include "file_utils.h" +#include "filemgmt_libhilog.h" +#include "fs_utils.h" + +namespace OHOS { +namespace FileManagement { +namespace ModuleFileIO { +using namespace std; + +#if !defined(WIN_PLATFORM) && !defined(IOS_PLATFORM) +static tuple> RealPathCore(const string &srcPath) +{ + std::unique_ptr realpathReq = { new (std::nothrow) uv_fs_t, + FsUtils::FsReqCleanup }; + if (!realpathReq) { + HILOGE("Failed to request heap memory."); + return { ENOMEM, move(realpathReq) }; + } + int ret = uv_fs_realpath(nullptr, realpathReq.get(), srcPath.c_str(), nullptr); + return { ret, move(realpathReq) }; +} + +void FsFile::RemoveEntity() +{ + fileEntity = nullptr; +} + +FsResult FsFile::GetFD() const +{ + if (!fileEntity) { + HILOGE("Failed to get file entity"); + return FsResult::Error(EINVAL); + } + return FsResult::Success(fileEntity->fd_.get()->GetFD()); +} + +FsResult FsFile::GetPath() const +{ + if (!fileEntity) { + HILOGE("Failed to get file entity"); + return FsResult::Error(EINVAL); + } + if (fileEntity->uri_.length() != 0) { + AppFileService::ModuleFileUri::FileUri fileUri(fileEntity->uri_); + return FsResult::Success(fileUri.GetPath()); + } + auto [realPathRes, realPath] = RealPathCore(fileEntity->path_); + if (realPathRes != ERRNO_NOERR) { + HILOGE("Failed to get real path"); + return FsResult::Error(realPathRes); + } + return FsResult::Success(string(static_cast(realPath->ptr))); +} + +FsResult FsFile::GetName() const +{ + if (!fileEntity) { + HILOGE("Failed to get file entity"); + return FsResult::Error(EINVAL); + } + if (fileEntity->uri_.length() != 0) { + AppFileService::ModuleFileUri::FileUri fileUri(fileEntity->uri_); + return FsResult::Success(fileUri.GetName()); + } + auto [realPathRes, realPath] = RealPathCore(fileEntity->path_); + if (realPathRes != ERRNO_NOERR) { + HILOGE("Failed to get real path"); + return FsResult::Error(realPathRes); + } + string path(static_cast(realPath->ptr)); + auto pos = path.find_last_of('/'); + if (pos == string::npos) { + HILOGE("Failed to split filename from path"); + return FsResult::Error(ENOENT); + } + return FsResult::Success(path.substr(pos + 1)); +} + +FsResult FsFile::GetParent() const +{ + if (!fileEntity) { + HILOGE("Failed to get file entity"); + return FsResult::Error(EINVAL); + } + + string path(fileEntity->path_); + if (fileEntity->uri_.length() != 0) { + AppFileService::ModuleFileUri::FileUri fileUri(fileEntity->uri_); + path = fileUri.GetPath(); + } else { + auto [realPathRes, realPath] = RealPathCore(path); + if (realPathRes) { + HILOGE("Failed to get real path"); + return FsResult::Error(realPathRes); + } + path = static_cast(realPath->ptr); + } + auto pos = path.find_last_of('/'); + if (pos == string::npos) { + HILOGE("Failed to split filename from path"); + return FsResult::Error(ENOENT); + } + return FsResult::Success(path.substr(0, pos)); +} + +FsResult FsFile::Lock(bool exclusive) const +{ + if (!fileEntity) { + HILOGE("Failed to get file entity"); + return FsResult::Error(EINVAL); + } + + if (!fileEntity || !fileEntity->fd_.get()) { + HILOGE("File has been closed in Lock cbExec possibly"); + return FsResult::Error(EIO); + } + int ret = 0; + auto mode = exclusive ? LOCK_EX : LOCK_SH; + ret = flock(fileEntity->fd_.get()->GetFD(), mode); + if (ret < 0) { + HILOGE("Failed to lock file"); + return FsResult::Error(errno); + } else { + return FsResult::Success(); + } +} + +FsResult FsFile::TryLock(bool exclusive) const +{ + if (!fileEntity) { + HILOGE("Failed to get file entity"); + return FsResult::Error(EINVAL); + } + + int ret = 0; + auto mode = static_cast(exclusive ? LOCK_EX : LOCK_SH); + ret = flock(fileEntity->fd_.get()->GetFD(), mode | LOCK_NB); + if (ret < 0) { + HILOGE("Failed to try to lock file"); + return FsResult::Error(errno); + } + + return FsResult::Success(); +} + +FsResult FsFile::UnLock() const +{ + if (!fileEntity) { + HILOGE("Failed to get file entity"); + return FsResult::Error(EINVAL); + } + + int ret = 0; + ret = flock(fileEntity->fd_.get()->GetFD(), LOCK_UN); + if (ret < 0) { + HILOGE("Failed to unlock file"); + return FsResult::Error(errno); + } + return FsResult::Success(); +} +#endif + +FsResult FsFile::Constructor() +{ + auto rafEntity = CreateUniquePtr(); + if (rafEntity == nullptr) { + HILOGE("Failed to request heap memory."); + return FsResult::Error(ENOMEM); + } + FsFile *fsFilePtr = new FsFile(move(rafEntity)); + + if (fsFilePtr == nullptr) { + HILOGE("Failed to create FsFile object on heap."); + return FsResult::Error(ENOMEM); + } + + return FsResult::Success(move(fsFilePtr)); +} + +} // namespace ModuleFileIO +} // namespace FileManagement +} // namespace OHOS \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fs/class_file/fs_file.h b/interfaces/kits/js/src/mod_fs/class_file/fs_file.h new file mode 100644 index 0000000000000000000000000000000000000000..6c8c2f8f035c57a614ab18d563ebc7ce394faa76 --- /dev/null +++ b/interfaces/kits/js/src/mod_fs/class_file/fs_file.h @@ -0,0 +1,76 @@ +/* +* Copyright (c) 2025 Huawei Device Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +#ifndef INTERFACES_KITS_JS_SRC_MOD_FS_CLASS_FILE_FS_FILE_H +#define INTERFACES_KITS_JS_SRC_MOD_FS_CLASS_FILE_FS_FILE_H + +#include "file_entity.h" +#include "filemgmt_libfs.h" + +namespace OHOS { +namespace FileManagement { +namespace ModuleFileIO { +using namespace std; + +class FsFile { +public: + inline static const string className_ = "File"; + + FileEntity *GetFileEntity() const + { + return fileEntity.get(); + } + + FsFile(const FsFile &other) = delete; + FsFile &operator=(const FsFile &other) = delete; + + FsFile(FsFile &&other) noexcept : fileEntity(move(other.fileEntity)) + { + other.fileEntity = nullptr; + } + + FsFile &operator=(FsFile &&other) noexcept + { + if (this != &other) { + fileEntity = move(other.fileEntity); + other.fileEntity = nullptr; + } + return *this; + } + + ~FsFile() = default; + +#if !defined(WIN_PLATFORM) && !defined(IOS_PLATFORM) + FsResult GetPath() const; + FsResult GetName() const; + FsResult GetParent() const; + FsResult Lock(bool exclusive = false) const; + FsResult TryLock(bool exclusive = false) const; + FsResult UnLock() const; +#endif + static FsResult Constructor(); + FsResult GetFD() const; + void RemoveEntity(); + +private: + unique_ptr fileEntity; + explicit FsFile(unique_ptr entity) : fileEntity(move(entity)) {} +}; + +const string PROCEDURE_LOCK_NAME = "FileIOFileLock"; +} // namespace ModuleFileIO +} // namespace FileManagement +} // namespace OHOS +#endif // INTERFACES_KITS_JS_SRC_MOD_FS_CLASS_FILE_FS_FILE_H \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fs/class_randomaccessfile/randomaccessfile_n_exporter.cpp b/interfaces/kits/js/src/mod_fs/class_randomaccessfile/randomaccessfile_n_exporter.cpp index bbe140fbb1839681212fdc407395cf9bcccac6c8..4a2350c680a66d92614a4fdafd33bd535f2153f2 100644 --- a/interfaces/kits/js/src/mod_fs/class_randomaccessfile/randomaccessfile_n_exporter.cpp +++ b/interfaces/kits/js/src/mod_fs/class_randomaccessfile/randomaccessfile_n_exporter.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023 Huawei Device Co., Ltd. + * Copyright (c) 2023-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -17,9 +17,9 @@ #include +#include "common_func.h" #include "file_utils.h" #include "randomaccessfile_entity.h" -#include "../common_func.h" namespace OHOS { namespace FileManagement { diff --git a/interfaces/kits/js/src/mod_fs/class_stat/ani/stat_ani.cpp b/interfaces/kits/js/src/mod_fs/class_stat/ani/stat_ani.cpp new file mode 100644 index 0000000000000000000000000000000000000000..de57367dac0ce3a7b45e197b77c96080c1c393ef --- /dev/null +++ b/interfaces/kits/js/src/mod_fs/class_stat/ani/stat_ani.cpp @@ -0,0 +1,147 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "stat_ani.h" + +#include "error_handler.h" +#include "filemgmt_libhilog.h" +#include "stat_core.h" +#include "stat_wrapper.h" +#include "type_converter.h" + +namespace OHOS { +namespace FileManagement { +namespace ModuleFileIO { +namespace ANI { +using namespace std; +using namespace OHOS::FileManagement::ModuleFileIO; + +ani_object StatAni::StatSync(ani_env *env, [[maybe_unused]] ani_class clazz, ani_object file) +{ + auto [succPath, fileInfo] = TypeConverter::ToFileInfo(env, file); + if (!succPath) { + HILOGE("The first argument requires filepath/fd"); + ErrorHandler::Throw(env, EINVAL); + return nullptr; + } + + auto ret = StatCore::DoStat(fileInfo); + if (!ret.IsSuccess()) { + HILOGE("DoStat failed!"); + const FsError &err = ret.GetError(); + ErrorHandler::Throw(env, err); + return nullptr; + } + + auto fsStat = ret.GetData().value(); + auto statObject = StatWrapper::Wrap(env, fsStat); + if (statObject == nullptr) { + delete fsStat; + fsStat = nullptr; + HILOGE("Wrap stat object failed!"); + ErrorHandler::Throw(env, UNKNOWN_ERR); + return nullptr; + } + + return statObject; +} + +ani_boolean StatAni::IsBlockDevice(ani_env *env, [[maybe_unused]] ani_object object) +{ + auto fsStat = StatWrapper::Unwrap(env, object); + if (fsStat == nullptr) { + ErrorHandler::Throw(env, UNKNOWN_ERR); + return ANI_FALSE; + } + + auto ret = fsStat->IsBlockDevice(); + return ani_boolean(ret); +} + +ani_boolean StatAni::IsCharacterDevice(ani_env *env, [[maybe_unused]] ani_object object) +{ + auto fsStat = StatWrapper::Unwrap(env, object); + if (fsStat == nullptr) { + ErrorHandler::Throw(env, UNKNOWN_ERR); + return ANI_FALSE; + } + + auto ret = fsStat->IsCharacterDevice(); + return ani_boolean(ret); +} + +ani_boolean StatAni::IsDirectory(ani_env *env, [[maybe_unused]] ani_object object) +{ + auto fsStat = StatWrapper::Unwrap(env, object); + if (fsStat == nullptr) { + ErrorHandler::Throw(env, UNKNOWN_ERR); + return ANI_FALSE; + } + + auto ret = fsStat->IsDirectory(); + return ani_boolean(ret); +} + +ani_boolean StatAni::IsFIFO(ani_env *env, [[maybe_unused]] ani_object object) +{ + auto fsStat = StatWrapper::Unwrap(env, object); + if (fsStat == nullptr) { + ErrorHandler::Throw(env, UNKNOWN_ERR); + return ANI_FALSE; + } + + auto ret = fsStat->IsFIFO(); + return ani_boolean(ret); +} + +ani_boolean StatAni::IsFile(ani_env *env, [[maybe_unused]] ani_object object) +{ + auto fsStat = StatWrapper::Unwrap(env, object); + if (fsStat == nullptr) { + ErrorHandler::Throw(env, UNKNOWN_ERR); + return ANI_FALSE; + } + + auto ret = fsStat->IsFile(); + return ani_boolean(ret); +} + +ani_boolean StatAni::IsSocket(ani_env *env, [[maybe_unused]] ani_object object) +{ + auto fsStat = StatWrapper::Unwrap(env, object); + if (fsStat == nullptr) { + ErrorHandler::Throw(env, UNKNOWN_ERR); + return ANI_FALSE; + } + + auto ret = fsStat->IsSocket(); + return ani_boolean(ret); +} + +ani_boolean StatAni::IsSymbolicLink(ani_env *env, [[maybe_unused]] ani_object object) +{ + auto fsStat = StatWrapper::Unwrap(env, object); + if (fsStat == nullptr) { + ErrorHandler::Throw(env, UNKNOWN_ERR); + return ANI_FALSE; + } + + auto ret = fsStat->IsSymbolicLink(); + return ani_boolean(ret); +} +} // namespace ANI +} // namespace ModuleFileIO +} // namespace FileManagement +} // namespace OHOS \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fs/class_stat/ani/stat_ani.h b/interfaces/kits/js/src/mod_fs/class_stat/ani/stat_ani.h new file mode 100644 index 0000000000000000000000000000000000000000..8fd891c720efb728048de1bb87344569f42f747f --- /dev/null +++ b/interfaces/kits/js/src/mod_fs/class_stat/ani/stat_ani.h @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef INTERFACES_KITS_JS_SRC_MOD_FS_PROPERTIES_ANI_STAT_ANI_H +#define INTERFACES_KITS_JS_SRC_MOD_FS_PROPERTIES_ANI_STAT_ANI_H + +#include + +namespace OHOS { +namespace FileManagement { +namespace ModuleFileIO { +namespace ANI { +class StatAni final { +public: + static ani_object StatSync(ani_env *env, [[maybe_unused]] ani_class clazz, ani_object file); + static ani_boolean IsBlockDevice(ani_env *env, [[maybe_unused]] ani_object object); + static ani_boolean IsCharacterDevice(ani_env *env, [[maybe_unused]] ani_object object); + static ani_boolean IsDirectory(ani_env *env, [[maybe_unused]] ani_object object); + static ani_boolean IsFIFO(ani_env *env, [[maybe_unused]] ani_object object); + static ani_boolean IsFile(ani_env *env, [[maybe_unused]] ani_object object); + static ani_boolean IsSocket(ani_env *env, [[maybe_unused]] ani_object object); + static ani_boolean IsSymbolicLink(ani_env *env, [[maybe_unused]] ani_object object); +}; +} // namespace ANI +} // namespace ModuleFileIO +} // namespace FileManagement +} // namespace OHOS +#endif // INTERFACES_KITS_JS_SRC_MOD_FS_PROPERTIES_ANI_STAT_ANI_H \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fs/class_stat/ani/stat_wrapper.cpp b/interfaces/kits/js/src/mod_fs/class_stat/ani/stat_wrapper.cpp new file mode 100644 index 0000000000000000000000000000000000000000..73e0a235cd142b56f3cd6b1c952b916f4add2292 --- /dev/null +++ b/interfaces/kits/js/src/mod_fs/class_stat/ani/stat_wrapper.cpp @@ -0,0 +1,237 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "stat_wrapper.h" + +#include +#include +#include + +#include "ani_signature.h" +#include "error_handler.h" +#include "filemgmt_libhilog.h" +#include "type_converter.h" + +namespace OHOS { +namespace FileManagement { +namespace ModuleFileIO { +namespace ANI { +using namespace std; +using namespace OHOS::FileManagement::ModuleFileIO; +using namespace OHOS::FileManagement::ModuleFileIO::ANI::AniSignature; + +static ani_status SetNumProperty( + ani_env *env, const ani_class &cls, ani_object &object, const char *name, ani_double &value) +{ + ani_method setter; + ani_status ret; + if ((ret = env->Class_FindMethod(cls, name, nullptr, &setter)) != ANI_OK) { + HILOGE("Class_FindMethod Fail %{private}s, err: %{private}d", name, ret); + return ret; + } + + return env->Object_CallMethod_Void(object, setter, value); +} + +static ani_status SetBigIntProperty( + ani_env *env, const ani_class &statCls, ani_object &statObject, const char *name, ani_double &value) +{ + ani_object object = {}; + auto classDesc = BuiltInTypes::BigInt::classDesc.c_str(); + ani_class cls; + ani_status ret; + + if ((ret = env->FindClass(classDesc, &cls)) != ANI_OK) { + HILOGE("Not found %{private}s, err: %{private}d", classDesc, ret); + return ret; + } + + auto ctorDesc = BuiltInTypes::BigInt::ctorDesc.c_str(); + auto ctorSig = BuiltInTypes::BigInt::ctorSig.c_str(); + ani_method ctor; + if (ANI_OK != env->Class_FindMethod(cls, ctorDesc, ctorSig, &ctor)) { + HILOGE("Not found ctor, err: %{private}d", ret); + return ret; + } + + if ((ret = env->Object_New(cls, ctor, &object, value)) != ANI_OK) { + HILOGE("New BigIntProperty Fail, err: %{private}d", ret); + return ret; + } + + ani_method setter; + if ((ret = env->Class_FindMethod(statCls, name, nullptr, &setter)) != ANI_OK) { + HILOGE("Class_FindMethod Fail %{private}s, err: %{private}d", name, ret); + return ret; + } + + return env->Object_CallMethod_Void(statObject, setter, object); +} + +static ani_enum_item GetLocationEnumIndex(ani_env *env, const Location &value) +{ + ani_enum enumType; + auto classDesc = FS::LocationType::classDesc.c_str(); + ani_status ret = env->FindEnum(classDesc, &enumType); + if (ret != ANI_OK) { + HILOGE("FindEnum %{private}s failed, err: %{private}d", classDesc, ret); + return nullptr; + } + + size_t valueAsSizeT = static_cast(value); + if (valueAsSizeT < 1) { + HILOGE("Invalid Location value: %{private}zu", valueAsSizeT); + return nullptr; + } + + size_t index = valueAsSizeT - 1; + + ani_enum_item enumItem; + ret = env->Enum_GetEnumItemByIndex(enumType, index, &enumItem); + if (ret != ANI_OK) { + HILOGE("Enum_GetEnumItemByIndex failed, index: %{private}zu, err: %{private}d", index, ret); + return nullptr; + } + return enumItem; +} + +static ani_status SetEnumLocation( + ani_env *env, const ani_class &cls, ani_object &object, const char *name, const Location &value) +{ + ani_method setter; + ani_status ret; + if ((ret = env->Class_FindMethod(cls, name, nullptr, &setter)) != ANI_OK) { + HILOGE("Class_FindMethod Fail %{private}s, err: %{private}d", name, ret); + return ret; + } + + return env->Object_CallMethod_Void(object, setter, GetLocationEnumIndex(env, value)); +} + +const static string MODE_SETTER = Builder::BuildSetterName("mode"); +const static string UID_SETTER = Builder::BuildSetterName("uid"); +const static string GID_SETTER = Builder::BuildSetterName("gid"); +const static string SIZE_SETTER = Builder::BuildSetterName("size"); +const static string ATIME_SETTER = Builder::BuildSetterName("atime"); +const static string MTIME_SETTER = Builder::BuildSetterName("mtime"); +const static string CTIME_SETTER = Builder::BuildSetterName("ctime"); +const static string INO_SETTER = Builder::BuildSetterName("ino"); +const static string ATIME_NS_SETTER = Builder::BuildSetterName("atimeNs"); +const static string MTIME_NS_SETTER = Builder::BuildSetterName("mtimeNs"); +const static string CTIME_NS_SETTER = Builder::BuildSetterName("ctimeNs"); +const static string LOCATION_SETTER = Builder::BuildSetterName("location"); + +static ani_status SetProperties(ani_env *env, const ani_class &cls, ani_object &statObject, FsStat *fsStat) +{ + ani_status ret; + + vector> numProperties = { + { MODE_SETTER, ani_double(static_cast(fsStat->GetMode())) }, + { UID_SETTER, ani_double(static_cast(fsStat->GetUid())) }, + { GID_SETTER, ani_double(static_cast(fsStat->GetGid())) }, + { SIZE_SETTER, ani_double(static_cast(fsStat->GetSize())) }, + { ATIME_SETTER, ani_double(static_cast(fsStat->GetAtime())) }, + { MTIME_SETTER, ani_double(static_cast(fsStat->GetMtime())) }, + { CTIME_SETTER, ani_double(static_cast(fsStat->GetCtime())) }, + }; + for (auto iter : numProperties) { + auto key = iter.first.data(); + auto value = iter.second; + ret = SetNumProperty(env, cls, statObject, key, value); + if (ret != ANI_OK) { + HILOGE("Object_CallMethod_Void Fail %{private}s, err: %{private}d", key, ret); + return ret; + } + } + + vector> bigIntProperties = { + { INO_SETTER, ani_double(static_cast(fsStat->GetIno())) }, + { ATIME_NS_SETTER, ani_double(static_cast(fsStat->GetAtimeNs())) }, + { MTIME_NS_SETTER, ani_double(static_cast(fsStat->GetMtimeNs())) }, + { CTIME_NS_SETTER, ani_double(static_cast(fsStat->GetCtimeNs())) }, + }; + for (auto iter : bigIntProperties) { + auto key = iter.first.data(); + auto value = iter.second; + ret = SetBigIntProperty(env, cls, statObject, key, value); + if (ret != ANI_OK) { + HILOGE("Object_CallMethod_Void Fail %{private}s, err: %{private}d", key, ret); + return ret; + } + } + +#if !defined(WIN_PLATFORM) && !defined(IOS_PLATFORM) + auto key = LOCATION_SETTER.c_str(); + if ((ret = SetEnumLocation(env, cls, statObject, key, static_cast(fsStat->GetLocation()))) != ANI_OK) { + HILOGE("Object_CallMethod_Void Fail %{private}s, err: %{private}d", key, ret); + return ret; + } +#endif + + return ANI_OK; +} + +ani_object StatWrapper::Wrap(ani_env *env, FsStat *fsStat) +{ + auto classDesc = FS::StatInner::classDesc.c_str(); + ani_object statObject = {}; + ani_class cls; + ani_status ret; + + if (fsStat == nullptr) { + HILOGE("FsStat pointer is null!"); + return nullptr; + } + + if ((ret = env->FindClass(classDesc, &cls)) != ANI_OK) { + HILOGE("Not found %{private}s, err: %{private}d", classDesc, ret); + return nullptr; + } + + auto ctorDesc = FS::StatInner::ctorDesc.c_str(); + auto ctorSig = FS::StatInner::ctorSig.c_str(); + ani_method ctor; + if (ANI_OK != env->Class_FindMethod(cls, ctorDesc, ctorSig, &ctor)) { + HILOGE("Not found ctor, err: %{private}d", ret); + return nullptr; + } + + if ((ret = env->Object_New(cls, ctor, &statObject, reinterpret_cast(fsStat))) != ANI_OK) { + HILOGE("New StatInner Fail, err: %{private}d", ret); + return nullptr; + } + + if ((ret = SetProperties(env, cls, statObject, fsStat)) != ANI_OK) { + HILOGE("SetProperties Fail, err: %{private}d", ret); + return nullptr; + } + + return statObject; +} + +FsStat *StatWrapper::Unwrap(ani_env *env, ani_object object) +{ + ani_long fsStat; + auto ret = env->Object_GetFieldByName_Long(object, "nativeStat", &fsStat); + if (ret != ANI_OK) { + HILOGE("Unwrap fsStat err: %{private}d", ret); + return nullptr; + } + return reinterpret_cast(fsStat); +} +} // namespace ANI +} // namespace ModuleFileIO +} // namespace FileManagement +} // namespace OHOS \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fs/class_stat/ani/stat_wrapper.h b/interfaces/kits/js/src/mod_fs/class_stat/ani/stat_wrapper.h new file mode 100644 index 0000000000000000000000000000000000000000..e84e1e5eb6561a31c7c2c5d14991531b2c8c0743 --- /dev/null +++ b/interfaces/kits/js/src/mod_fs/class_stat/ani/stat_wrapper.h @@ -0,0 +1,38 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef INTERFACES_KITS_JS_SRC_MOD_FS_PROPERTIES_ANI_STAT_WRAPPER_H +#define INTERFACES_KITS_JS_SRC_MOD_FS_PROPERTIES_ANI_STAT_WRAPPER_H + +#include + +#include "fs_stat.h" + +namespace OHOS { +namespace FileManagement { +namespace ModuleFileIO { +namespace ANI { +using namespace std; + +class StatWrapper final { +public: + static ani_object Wrap(ani_env *env, FsStat *fsStat); + static FsStat *Unwrap(ani_env *env, ani_object object); +}; +} // namespace ANI +} // namespace ModuleFileIO +} // namespace FileManagement +} // namespace OHOS +#endif // INTERFACES_KITS_JS_SRC_MOD_FS_PROPERTIES_ANI_STAT_WRAPPER_H \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fs/class_stat/fs_stat.cpp b/interfaces/kits/js/src/mod_fs/class_stat/fs_stat.cpp new file mode 100644 index 0000000000000000000000000000000000000000..4094dce3b003f1148ed358e841c354fcff3ddffd --- /dev/null +++ b/interfaces/kits/js/src/mod_fs/class_stat/fs_stat.cpp @@ -0,0 +1,171 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "fs_stat.h" + +#include +#include +#include +#include +#if !defined(WIN_PLATFORM) && !defined(IOS_PLATFORM) +#include +#endif + +#include "file_utils.h" +#include "filemgmt_libhilog.h" + +namespace OHOS::FileManagement::ModuleFileIO { +using namespace std; + +bool FsStat::CheckStatMode(mode_t mode) +{ + return (entity->stat_.st_mode & S_IFMT) == mode; +} + +bool FsStat::IsBlockDevice() +{ + return CheckStatMode(S_IFBLK); +} + +bool FsStat::IsCharacterDevice() +{ + return CheckStatMode(S_IFCHR); +} + +bool FsStat::IsDirectory() +{ + return CheckStatMode(S_IFDIR); +} + +bool FsStat::IsFIFO() +{ + return CheckStatMode(S_IFIFO); +} + +bool FsStat::IsFile() +{ + return CheckStatMode(S_IFREG); +} + +bool FsStat::IsSocket() +{ + return CheckStatMode(S_IFSOCK); +} + +bool FsStat::IsSymbolicLink() +{ + return CheckStatMode(S_IFLNK); +} + +int64_t FsStat::GetIno() +{ + return entity->stat_.st_ino; +} + +int64_t FsStat::GetMode() +{ + return entity->stat_.st_mode & S_PERMISSION; +} + +int64_t FsStat::GetUid() +{ + return entity->stat_.st_uid; +} + +int64_t FsStat::GetGid() +{ + return entity->stat_.st_gid; +} + +int64_t FsStat::GetSize() +{ + return entity->stat_.st_size; +} + +int64_t FsStat::GetAtime() +{ + return static_cast(entity->stat_.st_atim.tv_sec); +} + +int64_t FsStat::GetMtime() +{ + return static_cast(entity->stat_.st_mtim.tv_sec); +} + +int64_t FsStat::GetCtime() +{ + return static_cast(entity->stat_.st_ctim.tv_sec); +} + +int64_t FsStat::GetAtimeNs() +{ + return static_cast(entity->stat_.st_atim.tv_sec * SECOND_TO_NANOSECOND + entity->stat_.st_atim.tv_nsec); +} + +int64_t FsStat::GetMtimeNs() +{ + return static_cast(entity->stat_.st_mtim.tv_sec * SECOND_TO_NANOSECOND + entity->stat_.st_mtim.tv_nsec); +} + +int64_t FsStat::GetCtimeNs() +{ + return static_cast(entity->stat_.st_ctim.tv_sec * SECOND_TO_NANOSECOND + entity->stat_.st_ctim.tv_nsec); +} + +#if !defined(WIN_PLATFORM) && !defined(IOS_PLATFORM) +int32_t FsStat::GetLocation() +{ + std::unique_ptr value = CreateUniquePtr(MAX_ATTR_NAME); + if (value == nullptr) { + HILOGE("Getxattr memory out, errno is %{public}d", errno); + return ENOMEM; + } + + ssize_t size = 0; + if (entity->fileInfo_->isPath) { + size = getxattr(entity->fileInfo_->path.get(), CLOUD_LOCATION_ATTR.c_str(), value.get(), MAX_ATTR_NAME); + } else { + size = fgetxattr(entity->fileInfo_->fdg->GetFD(), CLOUD_LOCATION_ATTR.c_str(), value.get(), MAX_ATTR_NAME); + } + + Location defaultLocation = LOCAL; + if (size <= 0) { + if (errno != ENODATA && errno != EOPNOTSUPP) { + HILOGE("Getxattr value failed, errno is %{public}d", errno); + } + return static_cast(defaultLocation); + } + std::string location = string(value.get(), static_cast(size)); + if (!std::all_of(location.begin(), location.end(), ::isdigit)) { + HILOGE("Getxattr location is not all digit!"); + return static_cast(defaultLocation); + } + defaultLocation = static_cast(atoi(location.c_str())); + return static_cast(defaultLocation); +} +#endif + +FsStat *FsStat::Constructor() +{ + auto entity = CreateUniquePtr(); + if (entity == nullptr) { + HILOGE("Failed to request heap memory."); + return nullptr; + } + + return new FsStat(move(entity)); +} + +} // namespace OHOS::FileManagement::ModuleFileIO \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fs/class_stat/fs_stat.h b/interfaces/kits/js/src/mod_fs/class_stat/fs_stat.h new file mode 100644 index 0000000000000000000000000000000000000000..802015087cf5ad5f48c21e73b7179474c99390fa --- /dev/null +++ b/interfaces/kits/js/src/mod_fs/class_stat/fs_stat.h @@ -0,0 +1,69 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef INTERFACES_KITS_JS_SRC_MOD_FS_CLASS_STAT_FS_STAT_H +#define INTERFACES_KITS_JS_SRC_MOD_FS_CLASS_STAT_FS_STAT_H + +#include "filemgmt_libfs.h" +#include "fs_stat_entity.h" + +namespace OHOS::FileManagement::ModuleFileIO { +using namespace std; + +const int64_t SECOND_TO_NANOSECOND = 1e9; +constexpr int S_PERMISSION = 00000777; +#if !defined(WIN_PLATFORM) && !defined(IOS_PLATFORM) +const size_t MAX_ATTR_NAME = 64; +const std::string CLOUD_LOCATION_ATTR = "user.cloud.location"; +#endif +class FsStat final { +public: + static FsStat *Constructor(); + + StatEntity *GetStatEntity() const + { + return entity.get(); + } + + bool IsBlockDevice(); + bool IsCharacterDevice(); + bool IsDirectory(); + bool IsFIFO(); + bool IsFile(); + bool IsSocket(); + bool IsSymbolicLink(); + + int64_t GetIno(); + int64_t GetMode(); + int64_t GetUid(); + int64_t GetGid(); + int64_t GetSize(); + int64_t GetAtime(); + int64_t GetMtime(); + int64_t GetCtime(); + int64_t GetAtimeNs(); + int64_t GetMtimeNs(); + int64_t GetCtimeNs(); +#if !defined(WIN_PLATFORM) && !defined(IOS_PLATFORM) + int32_t GetLocation(); +#endif + +private: + unique_ptr entity; + bool CheckStatMode(mode_t mode); + explicit FsStat(unique_ptr entity) : entity(move(entity)) {}; +}; +} // namespace OHOS::FileManagement::ModuleFileIO +#endif // INTERFACES_KITS_JS_SRC_MOD_FS_CLASS_STAT_FS_STAT_H \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fs/class_stat/fs_stat_entity.h b/interfaces/kits/js/src/mod_fs/class_stat/fs_stat_entity.h new file mode 100644 index 0000000000000000000000000000000000000000..772bad4ed5698afabd54f77b776bb59fcb3da7ef --- /dev/null +++ b/interfaces/kits/js/src/mod_fs/class_stat/fs_stat_entity.h @@ -0,0 +1,34 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef INTERFACES_KITS_JS_SRC_MOD_FS_CLASS_STAT_FS_STAT_ENTITY_H +#define INTERFACES_KITS_JS_SRC_MOD_FS_CLASS_STAT_FS_STAT_ENTITY_H + +#include +#include "fs_utils.h" +#include "uv.h" + +#if !defined(WIN_PLATFORM) && !defined(IOS_PLATFORM) +enum Location { LOCAL = 1 << 0, CLOUD = 1 << 1 }; +#endif +namespace OHOS::FileManagement::ModuleFileIO { +struct StatEntity { + uv_stat_t stat_; +#if !defined(WIN_PLATFORM) && !defined(IOS_PLATFORM) + std::shared_ptr fileInfo_; +#endif +}; +} // namespace OHOS::FileManagement::ModuleFileIO +#endif // INTERFACES_KITS_JS_SRC_MOD_FS_CLASS_STAT_FS_STAT_ENTITY_H \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fs/class_stat/stat_instantiator.cpp b/interfaces/kits/js/src/mod_fs/class_stat/stat_instantiator.cpp new file mode 100644 index 0000000000000000000000000000000000000000..81e6a502e9bffd164ab8d05af725e2aa45618cf6 --- /dev/null +++ b/interfaces/kits/js/src/mod_fs/class_stat/stat_instantiator.cpp @@ -0,0 +1,53 @@ +/* +* Copyright (c) 2025 Huawei Device Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +#include "stat_instantiator.h" + +namespace OHOS { +namespace FileManagement { +namespace ModuleFileIO { +using namespace std; + +#if !defined(WIN_PLATFORM) && !defined(IOS_PLATFORM) +FsStat* StatInstantiator::InstantiateStat(const uv_stat_t &buf, shared_ptr fileInfo) +{ + auto stat = FsStat::Constructor(); + if (stat == nullptr) { + return nullptr; + } + + auto entity = stat->GetStatEntity(); + entity->stat_ = buf; + entity->fileInfo_ = fileInfo; + + return stat; +} +#endif + +FsStat* StatInstantiator::InstantiateStat(const uv_stat_t &buf) +{ + auto stat = FsStat::Constructor(); + if (stat == nullptr) { + return nullptr; + } + + auto entity = stat->GetStatEntity(); + entity->stat_ = buf; + + return stat; +} +} // namespace ModuleFileIO +} // namespace FileManagement +} // namespace OHOS \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fs/class_stat/stat_instantiator.h b/interfaces/kits/js/src/mod_fs/class_stat/stat_instantiator.h new file mode 100644 index 0000000000000000000000000000000000000000..384186885e3400c122a404b2220edf8d5d28d731 --- /dev/null +++ b/interfaces/kits/js/src/mod_fs/class_stat/stat_instantiator.h @@ -0,0 +1,38 @@ +/* +* Copyright (c) 2025 Huawei Device Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +#ifndef INTERFACES_KITS_JS_SRC_MOD_FS_CLASS_STAT_INSTANTIATOR_H +#define INTERFACES_KITS_JS_SRC_MOD_FS_CLASS_STAT_INSTANTIATOR_H + +#include "fs_stat.h" +#include "fs_utils.h" + +namespace OHOS { +namespace FileManagement { +namespace ModuleFileIO { +using namespace std; + +class StatInstantiator final { +public: +#if !defined(WIN_PLATFORM) && !defined(IOS_PLATFORM) + static FsStat* InstantiateStat(const uv_stat_t &buf, shared_ptr fileInfo); +#endif + static FsStat* InstantiateStat(const uv_stat_t &buf); +}; + +} // namespace ModuleFileIO +} // namespace FileManagement +} // namespace OHOS +#endif // INTERFACES_KITS_JS_SRC_MOD_FS_CLASS_STAT_INSTANTIATOR_H \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fs/class_watcher/watcher_n_exporter.cpp b/interfaces/kits/js/src/mod_fs/class_watcher/watcher_n_exporter.cpp index ea1d95224eb9cd30eea1e22d9fa7cd6526814a9f..18afa4652d7d595188ab004d22890bd2e8fa2790 100644 --- a/interfaces/kits/js/src/mod_fs/class_watcher/watcher_n_exporter.cpp +++ b/interfaces/kits/js/src/mod_fs/class_watcher/watcher_n_exporter.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023 Huawei Device Co., Ltd. + * Copyright (c) 2023-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -20,10 +20,10 @@ #include #include -#include "../common_func.h" +#include "common_func.h" #include "file_utils.h" -#include "filemgmt_libn.h" #include "filemgmt_libhilog.h" +#include "filemgmt_libn.h" #include "securec.h" namespace OHOS::FileManagement::ModuleFileIO { diff --git a/interfaces/kits/js/src/mod_fs/fs_utils.cpp b/interfaces/kits/js/src/mod_fs/fs_utils.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d8331b21bc4480a94e9b1c0acdf3b52035a1a268 --- /dev/null +++ b/interfaces/kits/js/src/mod_fs/fs_utils.cpp @@ -0,0 +1,119 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "fs_utils.h" +#include "filemgmt_libhilog.h" + +namespace OHOS::FileManagement::ModuleFileIO { +using namespace std; + +namespace { +const vector PUBLIC_DIR_PATHS = { "/Documents" }; +} + +tuple FsUtils::GetActualLen(size_t bufLen, size_t bufOff, const optional &length) +{ + if (bufLen < bufOff) { + HILOGE( + "Illegal parameter value: bufLen (%{public}zu) cannot be less than bufOff (%{public}zu)", bufLen, bufOff); + return { false, 0 }; + } + + size_t retLen = bufLen - bufOff; + + if (length.has_value()) { + int64_t opLength = length.value(); + if (opLength < 0 || static_cast(opLength) > retLen) { + HILOGE("Invalid option.length: option.length=%{public}" PRId64 ", retLen=%{public}zu", opLength, retLen); + return { false, 0 }; + } + retLen = static_cast(opLength); + } + return { true, retLen }; +} + +uint32_t FsUtils::ConvertFlags(const uint32_t &flags) +{ + // default value is usrReadOnly 00 + uint32_t flagsABI = 0; + flagsABI |= ((flags & USR_WRITE_ONLY) == USR_WRITE_ONLY) ? WRONLY : 0; + flagsABI |= ((flags & USR_RDWR) == USR_RDWR) ? RDWR : 0; + flagsABI |= ((flags & USR_CREATE) == USR_CREATE) ? CREATE : 0; + flagsABI |= ((flags & USR_TRUNC) == USR_TRUNC) ? TRUNC : 0; + flagsABI |= ((flags & USR_APPEND) == USR_APPEND) ? APPEND : 0; + flagsABI |= ((flags & USR_NONBLOCK) == USR_NONBLOCK) ? NONBLOCK : 0; + flagsABI |= ((flags & USR_DIRECTORY) == USR_DIRECTORY) ? DIRECTORY : 0; + flagsABI |= ((flags & USR_NOFOLLOW) == USR_NOFOLLOW) ? NOFOLLOW : 0; + flagsABI |= ((flags & USR_SYNC) == USR_SYNC) ? SYNC : 0; + return flagsABI; +} + +void FsUtils::FsReqCleanup(uv_fs_t *req) +{ + uv_fs_req_cleanup(req); + if (req) { + delete req; + req = nullptr; + } +} + +string FsUtils::GetModeFromFlags(const uint32_t &flags) +{ + const string readMode = "r"; + const string writeMode = "w"; + const string appendMode = "a"; + const string truncMode = "t"; + string mode = readMode; + mode += (((flags & O_RDWR) == O_RDWR) ? writeMode : ""); + mode = (((flags & O_WRONLY) == O_WRONLY) ? writeMode : mode); + if (mode != readMode) { + mode += ((flags & O_TRUNC) ? truncMode : ""); + mode += ((flags & O_APPEND) ? appendMode : ""); + } + return mode; +} + +bool FsUtils::CheckPublicDirPath(const string &sandboxPath) +{ + for (const string &path : PUBLIC_DIR_PATHS) { + if (sandboxPath.find(path) == 0) { + return true; + } + } + return false; +} + +string FsUtils::Decode(const string &uri) +{ + ostringstream outPutStream; + const int32_t encodeLen = 2; + size_t index = 0; + while (index < uri.length()) { + if (uri[index] == '%') { + int hex = 0; + istringstream inputStream(uri.substr(index + 1, encodeLen)); + inputStream >> hex >> hex; + outPutStream << static_cast(hex); + index += encodeLen + 1; + } else { + outPutStream << uri[index]; + index++; + } + } + + return outPutStream.str(); +} + +} // namespace OHOS::FileManagement::ModuleFileIO diff --git a/interfaces/kits/js/src/mod_fs/fs_utils.h b/interfaces/kits/js/src/mod_fs/fs_utils.h new file mode 100644 index 0000000000000000000000000000000000000000..f67e374284ef8a94594f1f50afa91fd0b1b33286 --- /dev/null +++ b/interfaces/kits/js/src/mod_fs/fs_utils.h @@ -0,0 +1,99 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef INTERFACES_KITS_JS_SRC_MOD_FS_FS_UTILS_H +#define INTERFACES_KITS_JS_SRC_MOD_FS_FS_UTILS_H + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +#include "fd_guard.h" +#include "uv.h" + +#if !defined(WIN_PLATFORM) && !defined(IOS_PLATFORM) +#include "iremote_broker.h" +#endif + +namespace OHOS::FileManagement::ModuleFileIO { +using namespace std; + +constexpr int32_t RDONLY = UV_FS_O_RDONLY; +constexpr int32_t WRONLY = UV_FS_O_WRONLY; +constexpr int32_t RDWR = UV_FS_O_RDWR; +constexpr int32_t CREATE = UV_FS_O_CREAT; +constexpr int32_t TRUNC = UV_FS_O_TRUNC; +constexpr int32_t APPEND = UV_FS_O_APPEND; +constexpr int32_t NONBLOCK = UV_FS_O_NONBLOCK; +constexpr int32_t DIRECTORY = UV_FS_O_DIRECTORY; +constexpr int32_t NOFOLLOW = UV_FS_O_NOFOLLOW; +constexpr int32_t SYNC = UV_FS_O_SYNC; + +constexpr uint32_t MODE_EXIST = 00; +constexpr uint32_t MODE_WRITE = 02; +constexpr uint32_t MODE_READ = 04; +constexpr uint32_t MODE_READ_WRITE = 06; + +constexpr uint32_t USR_READ_ONLY = 00; +constexpr uint32_t USR_WRITE_ONLY = 01; +constexpr uint32_t USR_RDWR = 02; +constexpr uint32_t USR_CREATE = 0100; +constexpr uint32_t USR_TRUNC = 01000; +constexpr uint32_t USR_APPEND = 02000; +constexpr uint32_t USR_NONBLOCK = 04000; +constexpr uint32_t USR_DIRECTORY = 0200000; +constexpr uint32_t USR_NOFOLLOW = 0400000; +constexpr uint32_t USR_SYNC = 04010000; + +const double NS = 1e9; +const double MS = 1e3; + +struct FileInfo { + bool isPath = false; + unique_ptr path = { nullptr }; + unique_ptr fdg = { nullptr }; +}; + +#if !defined(WIN_PLATFORM) && !defined(IOS_PLATFORM) +class FileIoToken : public IRemoteBroker { +public: + DECLARE_INTERFACE_DESCRIPTOR(u"ohos.fileio.open"); + + FileIoToken() = default; + virtual ~FileIoToken() noexcept = default; +}; +#endif + +class FsUtils { +public: + static tuple GetActualLen(size_t bufLen, size_t bufOff, const optional &length = nullopt); + static uint32_t ConvertFlags(const uint32_t &flags); + static void FsReqCleanup(uv_fs_t *req); + static string GetModeFromFlags(const uint32_t &flags); + static bool CheckPublicDirPath(const string &sandboxPath); + static string Decode(const string &uri); +}; + +} // namespace OHOS::FileManagement::ModuleFileIO +#endif // INTERFACES_KITS_JS_SRC_MOD_FS_FS_UTILS_H diff --git a/interfaces/kits/js/src/mod_fs/properties/access_core.cpp b/interfaces/kits/js/src/mod_fs/properties/access_core.cpp new file mode 100644 index 0000000000000000000000000000000000000000..7253e41fdd77f2080fc10a7ecd39e82a1fb5bfe3 --- /dev/null +++ b/interfaces/kits/js/src/mod_fs/properties/access_core.cpp @@ -0,0 +1,217 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "access_core.h" + +#include + +#if !defined(WIN_PLATFORM) && !defined(IOS_PLATFORM) +#include + +#include "bundle_mgr_proxy.h" +#include "if_system_ability_manager.h" +#include "ipc_skeleton.h" +#include "iservice_registry.h" +#include "rust_file.h" +#include "system_ability_definition.h" + +#endif + +#ifdef FILE_API_TRACE +#include "hitrace_meter.h" +#endif + +#include "filemgmt_libhilog.h" + +namespace OHOS { +namespace FileManagement { +namespace ModuleFileIO { +using namespace std; +using namespace AppExecFwk; + +#if !defined(WIN_PLATFORM) && !defined(IOS_PLATFORM) +const string CLOUDDISK_FILE_PREFIX = "/data/storage/el2/cloud"; +const string DISTRIBUTED_FILE_PREFIX = "/data/storage/el2/distributedfiles"; +const string PACKAGE_NAME_FLAG = ""; +const string USER_ID_FLAG = ""; +const string PHYSICAL_PATH_PREFIX = "/mnt/hmdfs//account/device_view/local/data/"; +const string CLOUD_FILE_LOCATION = "user.cloud.location"; +const char POSITION_LOCAL = '1'; +const char POSITION_BOTH = '3'; +const int BASE_USER_RANGE = 200000; +#endif + +static int UvAccess(const string &path, int mode) +{ + std::unique_ptr accessReq = {new uv_fs_t, FsUtils::FsReqCleanup}; + if (!accessReq) { + HILOGE("Failed to request heap memory."); + return ENOMEM; + } + return uv_fs_access(nullptr, accessReq.get(), path.c_str(), mode, nullptr); +} + +#if !defined(WIN_PLATFORM) && !defined(IOS_PLATFORM) +static bool IsCloudOrDistributedFilePath(const string &path) +{ + return path.find(CLOUDDISK_FILE_PREFIX) == 0 || path.find(DISTRIBUTED_FILE_PREFIX) == 0; +} + +static int GetCurrentUserId() +{ + int uid = IPCSkeleton::GetCallingUid(); + int userId = uid / BASE_USER_RANGE; + return userId; +} + +static sptr GetBundleMgrProxy() +{ + sptr systemAbilityManager = + SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); + if (!systemAbilityManager) { + HILOGE("fail to get system ability mgr"); + return nullptr; + } + sptr remoteObject = systemAbilityManager->GetSystemAbility(BUNDLE_MGR_SERVICE_SYS_ABILITY_ID); + if (!remoteObject) { + HILOGE("fail to get bundle manager proxy"); + return nullptr; + } + + return iface_cast(remoteObject); +} + +static string GetSelfBundleName() +{ + sptr bundleMgrProxy = GetBundleMgrProxy(); + if (!bundleMgrProxy) { + HILOGE("bundleMgrProxy is nullptr"); + return ""; + } + BundleInfo bundleInfo; + auto ret = bundleMgrProxy->GetBundleInfoForSelf(0, bundleInfo); + if (ret != 0) { + HILOGE("bundleName get fail"); + return ""; + } + return bundleInfo.name; +} + +static int HandleLocalCheck(const string &path, int mode) +{ + // check if the file of /data/storage/el2/cloud is on the local + if (path.find(CLOUDDISK_FILE_PREFIX) == 0) { + char val[2] = {'\0'}; + if (getxattr(path.c_str(), CLOUD_FILE_LOCATION.c_str(), val, sizeof(val)) < 0) { + HILOGI("get cloud file location fail, err: %{public}d", errno); + return errno; + } + if (val[0] == POSITION_LOCAL || val[0] == POSITION_BOTH) { + return 0; + } + return ENOENT; + } + // check if the distributed file of /data/storage/el2/distributedfiles is on the local, + // convert into physical path(/mnt/hmdfs//account/device_view/local/data/) and check + if (path.find(DISTRIBUTED_FILE_PREFIX) == 0) { + int userId = GetCurrentUserId(); + string bundleName = GetSelfBundleName(); + string relativePath = path.substr(DISTRIBUTED_FILE_PREFIX.length()); + string physicalPath = PHYSICAL_PATH_PREFIX + relativePath; + physicalPath.replace(physicalPath.find(USER_ID_FLAG), USER_ID_FLAG.length(), to_string(userId)); + physicalPath.replace(physicalPath.find(PACKAGE_NAME_FLAG), PACKAGE_NAME_FLAG.length(), bundleName); + + return UvAccess(physicalPath, mode); + } + + return ENOENT; +} +#endif + +static int Access(const string &path, int mode, int flag) +{ +#if !defined(WIN_PLATFORM) && !defined(IOS_PLATFORM) + if (flag == LOCAL_FLAG && IsCloudOrDistributedFilePath(path)) { + return HandleLocalCheck(path, mode); + } +#endif + return UvAccess(path, mode); +} + +static int GetMode(const std::optional &modeOpt, bool *hasMode) +{ + if (modeOpt.has_value()) { + int mode = static_cast(modeOpt.value()); + *hasMode = true; + if ((static_cast(mode) & 0x06) == static_cast(mode)) { + return mode; + } + } + + return -1; +} + +static bool ValidAccessArgs(const std::string &path, const std::optional &modeOpt, + int &finalMode) +{ + if (path.empty()) { + HILOGE("Invalid path"); + return false; + } + bool hasMode = false; + int mode = GetMode(modeOpt, &hasMode); + if (mode < 0 && hasMode) { + HILOGE("Invalid mode"); + return false; + } + finalMode = hasMode ? mode : 0; + return true; +} + +FsResult AccessCore::DoAccess(const std::string& path, const std::optional &mode) +{ + int finalMode = 0; + int flag = DEFAULT_FLAG; + if (!ValidAccessArgs(path, mode, finalMode)) { + return FsResult::Error(EINVAL); + } + int ret = Access(path, finalMode, flag); + if (ret < 0 && (std::string_view(uv_err_name(ret)) != "ENOENT")) { + HILOGE("Failed to access file by path"); + return FsResult::Error(ret); + } + bool isAccess = (ret == 0); + return FsResult::Success(isAccess); +} + +FsResult AccessCore::DoAccess(const std::string& path, const AccessModeType &mode, const AccessFlag &flag) +{ + int finalMode = static_cast(mode); + int finalFlag = static_cast(flag); + if (!ValidAccessArgs(path, std::make_optional(mode), finalMode)) { + return FsResult::Error(EINVAL); + } + int ret = Access(path, finalMode, finalFlag); + if (ret < 0 && (std::string_view(uv_err_name(ret)) != "ENOENT")) { + HILOGE("Failed to access file by path"); + return FsResult::Error(ret); + } + bool isAccess = (ret == 0); + return FsResult::Success(isAccess); +} + +} // namespace ModuleFileIO +} // namespace FileManagement +} // namespace OHOS \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fs/properties/access_core.h b/interfaces/kits/js/src/mod_fs/properties/access_core.h new file mode 100644 index 0000000000000000000000000000000000000000..ea3ee3c1323d941d7e39d003db8b8f5f5b5b0d47 --- /dev/null +++ b/interfaces/kits/js/src/mod_fs/properties/access_core.h @@ -0,0 +1,45 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef INTERFACES_KITS_JS_SRC_MOD_FS_PROPERTIES_ACCESS_CORE_H +#define INTERFACES_KITS_JS_SRC_MOD_FS_PROPERTIES_ACCESS_CORE_H + +#include "filemgmt_libfs.h" +#include "fs_utils.h" + +namespace OHOS { +namespace FileManagement { +namespace ModuleFileIO { +using namespace std; + +enum class AccessModeType { ERROR = -1, EXIST = 0, WRITE = 2, READ = 4, READ_WRITE = 6 }; + +enum AccessFlag : int32_t { + DEFAULT_FLAG = -1, + LOCAL_FLAG, +}; + +class AccessCore { +public: + inline static const string className_ = "__properities__"; + + static FsResult DoAccess(const string &path, const optional &mode = nullopt); + static FsResult DoAccess(const string &path, const AccessModeType &mode, const AccessFlag &flag); +}; + +} // namespace ModuleFileIO +} // namespace FileManagement +} // namespace OHOS +#endif // INTERFACES_KITS_JS_SRC_MOD_FS_PROPERTIES_ACCESS_CORE_H \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fs/properties/ani/access_ani.cpp b/interfaces/kits/js/src/mod_fs/properties/ani/access_ani.cpp new file mode 100644 index 0000000000000000000000000000000000000000..41052ff71a9b15e57bd6f24f390653572ee451fc --- /dev/null +++ b/interfaces/kits/js/src/mod_fs/properties/ani/access_ani.cpp @@ -0,0 +1,123 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "access_ani.h" + +#include "access_core.h" +#include "error_handler.h" +#include "filemgmt_libhilog.h" +#include "type_converter.h" + +namespace OHOS { +namespace FileManagement { +namespace ModuleFileIO { +namespace ANI { + +static constexpr int EXIST_INDEX = 0; +static constexpr int WRITE_INDEX = 2; +static constexpr int READ_INDEX = 4; +static constexpr int READ_WRITE_INDEX = 6; + +static constexpr int LOCAL_INDEX = 0; + +AccessModeType ToAccessModeType(int32_t mode_index) +{ + switch (mode_index) { + case EXIST_INDEX: + return AccessModeType::EXIST; + case WRITE_INDEX: + return AccessModeType::WRITE; + case READ_INDEX: + return AccessModeType::READ; + case READ_WRITE_INDEX: + return AccessModeType::READ_WRITE; + default: + return AccessModeType::ERROR; + } +} + +std::optional OptToAccessModeType(const std::optional &mode_index) +{ + if (!mode_index.has_value()) { + return std::nullopt; + } + return ToAccessModeType(mode_index.value()); +} + +AccessFlag ToAccessFlagType(int32_t flag_index) +{ + switch (flag_index) { + case LOCAL_INDEX: + return AccessFlag::LOCAL_FLAG; + default: + return AccessFlag::DEFAULT_FLAG; + } +} + +std::optional OptToAccessFlagType(const std::optional &flag_index) +{ + if (!flag_index.has_value()) { + return std::nullopt; + } + return ToAccessFlagType(flag_index.value()); +} + +ani_boolean AccessAni::AccessSync3( + ani_env *env, [[maybe_unused]] ani_class clazz, ani_string path, ani_enum_item mode, ani_enum_item flag) +{ + ani_boolean ret = 0; + auto [succPath, pathStr] = TypeConverter::ToUTF8String(env, path); + if (!succPath) { + HILOGE("Invalid path"); + ErrorHandler::Throw(env, EINVAL); + return ret; + } + + auto [succMode, modeOp] = TypeConverter::EnumToInt32(env, mode); + if (!succMode) { + HILOGE("Invalid mode"); + ErrorHandler::Throw(env, EINVAL); + return ret; + } + auto modeType = OptToAccessModeType(modeOp); + + auto [succFlag, flagOpt] = TypeConverter::EnumToInt32(env, flag); + if (!succFlag) { + HILOGE("Invalid flag"); + ErrorHandler::Throw(env, EINVAL); + return ret; + } + auto flagType = OptToAccessFlagType(flagOpt); + + FsResult fsRet = FsResult::Error(UNKNOWN_ERR); + if (modeType != std::nullopt && flagType != std::nullopt) { + fsRet = AccessCore::DoAccess(pathStr, modeType.value(), flagType.value()); + } else { + fsRet = AccessCore::DoAccess(pathStr, modeType); + } + + if (!fsRet.IsSuccess()) { + HILOGE("DoAccess failed"); + const auto &err = fsRet.GetError(); + ErrorHandler::Throw(env, err); + return false; + } + return fsRet.GetData().value(); +} + +} // namespace ANI +} // namespace ModuleFileIO +} // namespace FileManagement +} // namespace OHOS \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fs/properties/ani/access_ani.h b/interfaces/kits/js/src/mod_fs/properties/ani/access_ani.h new file mode 100644 index 0000000000000000000000000000000000000000..e95093ee66c71b3d74760ecf2157294fa24c5931 --- /dev/null +++ b/interfaces/kits/js/src/mod_fs/properties/ani/access_ani.h @@ -0,0 +1,36 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef INTERFACES_KITS_JS_SRC_MOD_FS_PROPERTIES_ANI_ACCESS_ANI_H +#define INTERFACES_KITS_JS_SRC_MOD_FS_PROPERTIES_ANI_ACCESS_ANI_H + +#include + +namespace OHOS { +namespace FileManagement { +namespace ModuleFileIO { +namespace ANI { + +class AccessAni final { +public: + static ani_boolean AccessSync3( + ani_env *env, [[maybe_unused]] ani_class clazz, ani_string path, ani_enum_item mode, ani_enum_item flag); +}; +} // namespace ANI +} // namespace ModuleFileIO +} // namespace FileManagement +} // namespace OHOS + +#endif // INTERFACES_KITS_JS_SRC_MOD_FS_PROPERTIES_ANI_ACCESS_ANI_H \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fs/properties/ani/close_ani.cpp b/interfaces/kits/js/src/mod_fs/properties/ani/close_ani.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ab03c25250a60487492a3242253fa010fd22d6fb --- /dev/null +++ b/interfaces/kits/js/src/mod_fs/properties/ani/close_ani.cpp @@ -0,0 +1,96 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "close_ani.h" + +#include + +#include "ani_signature.h" +#include "close_core.h" +#include "error_handler.h" +#include "filemgmt_libhilog.h" +#include "file_wrapper.h" +#include "type_converter.h" + +namespace OHOS { +namespace FileManagement { +namespace ModuleFileIO { +namespace ANI { + +using namespace std; +using namespace OHOS::FileManagement::ModuleFileIO; +using namespace OHOS::FileManagement::ModuleFileIO::ANI::AniSignature; + +tuple ParseFdOrFile(ani_env *env, ani_object obj) +{ + int32_t result = -1; + auto doubleClassDesc = BoxedTypes::Double::classDesc.c_str(); + ani_class doubleClass; + env->FindClass(doubleClassDesc, &doubleClass); + ani_boolean isDouble; + env->Object_InstanceOf(obj, doubleClass, &isDouble); + if (isDouble) { + ani_int fd; + if (ANI_OK != env->Object_CallMethodByName_Int(obj, "intValue", nullptr, &fd)) { + HILOGE("Get fd value failed"); + return { false, result, nullptr }; + } + result = static_cast(fd); + return { true, result, nullptr }; + } + + FsFile *file = FileWrapper::Unwrap(env, obj); + if (file != nullptr) { + return { true, -1, file }; + } + + HILOGE("Cannot unwrap fsfile!"); + ErrorHandler::Throw(env, UNKNOWN_ERR); + return { false, -1, nullptr }; +} + +void CloseAni::CloseSync(ani_env *env, [[maybe_unused]] ani_class clazz, ani_object obj) +{ + auto [succ, fd, file] = ParseFdOrFile(env, obj); + if (!succ) { + HILOGE("Parse fd argument failed"); + ErrorHandler::Throw(env, EINVAL); + return; + } + + if (file == nullptr) { + auto ret = CloseCore::DoClose(fd); + if (!ret.IsSuccess()) { + HILOGE("Close %d failed", fd); + const auto &err = ret.GetError(); + ErrorHandler::Throw(env, err); + return; + } + return; + } + + auto ret = CloseCore::DoClose(file); + if (!ret.IsSuccess()) { + HILOGE("Close %d failed", fd); + const auto &err = ret.GetError(); + ErrorHandler::Throw(env, err); + return; + } +} + +} // namespace ANI +} // namespace ModuleFileIO +} // namespace FileManagement +} // namespace OHOS \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fs/properties/ani/close_ani.h b/interfaces/kits/js/src/mod_fs/properties/ani/close_ani.h new file mode 100644 index 0000000000000000000000000000000000000000..aa3fa07196722bd065633ce047837ed21603a932 --- /dev/null +++ b/interfaces/kits/js/src/mod_fs/properties/ani/close_ani.h @@ -0,0 +1,36 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef INTERFACES_KITS_JS_SRC_MOD_FS_PROPERTIES_ANI_CLOSE_ANI_H +#define INTERFACES_KITS_JS_SRC_MOD_FS_PROPERTIES_ANI_CLOSE_ANI_H + +#include + +namespace OHOS { +namespace FileManagement { +namespace ModuleFileIO { +namespace ANI { + +class CloseAni final { +public: + static void CloseSync(ani_env *env, [[maybe_unused]] ani_class clazz, ani_object obj); +}; + +} // namespace ANI +} // namespace ModuleFileIO +} // namespace FileManagement +} // namespace OHOS + +#endif // INTERFACES_KITS_JS_SRC_MOD_FS_PROPERTIES_ANI_CLOSE_ANI_H \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fs/properties/ani/copy_file_ani.cpp b/interfaces/kits/js/src/mod_fs/properties/ani/copy_file_ani.cpp new file mode 100644 index 0000000000000000000000000000000000000000..51e30f4de0053763d7b6c0d812c6c4d1b1eaf554 --- /dev/null +++ b/interfaces/kits/js/src/mod_fs/properties/ani/copy_file_ani.cpp @@ -0,0 +1,59 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "copy_file_ani.h" + +#include "copy_file_core.h" +#include "error_handler.h" +#include "filemgmt_libhilog.h" +#include "type_converter.h" + +namespace OHOS { +namespace FileManagement { +namespace ModuleFileIO { +namespace ANI { +using namespace std; +using namespace OHOS::FileManagement::ModuleFileIO; + +void CopyFileAni::CopyFileSync( + ani_env *env, [[maybe_unused]] ani_class clazz, ani_object src, ani_object dest, ani_object mode) +{ + auto [succSrc, srcFile] = TypeConverter::ToFileInfo(env, src); + auto [succDest, destFile] = TypeConverter::ToFileInfo(env, dest); + if (!succSrc || !succDest) { + HILOGE("The first/second argument requires filepath/fd"); + ErrorHandler::Throw(env, EINVAL); + return; + } + + auto [succMode, optMode] = TypeConverter::ToOptionalInt32(env, mode); + if (!succMode) { + HILOGE("Failed to convert mode to int32"); + ErrorHandler::Throw(env, EINVAL); + return; + } + + auto ret = CopyFileCore::DoCopyFile(srcFile, destFile, optMode); + if (!ret.IsSuccess()) { + HILOGE("DoCopyFile failed!"); + const FsError &err = ret.GetError(); + ErrorHandler::Throw(env, err); + return; + } +} +} // namespace ANI +} // namespace ModuleFileIO +} // namespace FileManagement +} // namespace OHOS \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fs/properties/ani/copy_file_ani.h b/interfaces/kits/js/src/mod_fs/properties/ani/copy_file_ani.h new file mode 100644 index 0000000000000000000000000000000000000000..ce5c5c168a4b87d0e222682c541cffca11977d6f --- /dev/null +++ b/interfaces/kits/js/src/mod_fs/properties/ani/copy_file_ani.h @@ -0,0 +1,34 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef INTERFACES_KITS_JS_SRC_MOD_FS_PROPERTIES_ANI_COPY_FILE_ANI_H +#define INTERFACES_KITS_JS_SRC_MOD_FS_PROPERTIES_ANI_COPY_FILE_ANI_H + +#include + +namespace OHOS { +namespace FileManagement { +namespace ModuleFileIO { +namespace ANI { +class CopyFileAni final { +public: + static void CopyFileSync( + ani_env *env, [[maybe_unused]] ani_class clazz, ani_object src, ani_object dest, ani_object mode); +}; +} // namespace ANI +} // namespace ModuleFileIO +} // namespace FileManagement +} // namespace OHOS +#endif // INTERFACES_KITS_JS_SRC_MOD_FS_PROPERTIES_ANI_COPY_FILE_ANI_H \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fs/properties/ani/listfile_ani.cpp b/interfaces/kits/js/src/mod_fs/properties/ani/listfile_ani.cpp new file mode 100644 index 0000000000000000000000000000000000000000..43527ee474abfda13cfb1e53e14ccd918dac774f --- /dev/null +++ b/interfaces/kits/js/src/mod_fs/properties/ani/listfile_ani.cpp @@ -0,0 +1,247 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "listfile_ani.h" + +#include "ani_signature.h" +#include "error_handler.h" +#include "filemgmt_libhilog.h" +#include "listfile_core.h" +#include "type_converter.h" + +namespace OHOS { +namespace FileManagement { +namespace ModuleFileIO { +namespace ANI { + +using namespace std; +using namespace OHOS::FileManagement::ModuleFileIO; +using namespace OHOS::FileManagement::ModuleFileIO::ANI::AniSignature; + +tuple ParseBooleanParam(ani_env *env, ani_object obj, string tag) +{ + ani_ref boolRef; + ani_boolean isUndefined; + if (ANI_OK != env->Object_GetPropertyByName_Ref(obj, tag.c_str(), &boolRef)) { + return { false, false }; + } + env->Reference_IsUndefined(boolRef, &isUndefined); + if (isUndefined) { + return { true, false }; + } + auto unboxedDesc = BoxedTypes::Boolean::unboxedDesc.c_str(); + auto unboxedSig = BoxedTypes::Boolean::unboxedSig.c_str(); + ani_boolean boolRef_res; + if (ANI_OK != env->Object_CallMethodByName_Boolean( + static_cast(boolRef), unboxedDesc, unboxedSig, &boolRef_res)) { + return { false, false }; + } + return { true, static_cast(boolRef_res) }; +} + +tuple ParseIntParam(ani_env *env, ani_object obj, string tag) +{ + int result = 0; + ani_boolean isUndefined; + ani_ref resultRef; + if (ANI_OK != env->Object_GetPropertyByName_Ref(obj, tag.c_str(), &resultRef)) { + return { false, result }; + } + env->Reference_IsUndefined(resultRef, &isUndefined); + if (isUndefined) { + return { true, result }; + } + ani_int resultRefRes; + if (ANI_OK != env->Object_CallMethodByName_Int( + static_cast(resultRef), "intValue", nullptr, &resultRefRes)) { + result = -1; + return { false, result }; + } + result = static_cast(resultRefRes); + return { true, result }; +} + +tuple> ParseDoubleParam(ani_env *env, ani_object obj, string tag) +{ + ani_boolean isUndefined; + ani_ref resultRef; + if (ANI_OK != env->Object_GetPropertyByName_Ref(obj, tag.c_str(), &resultRef)) { + return { false, nullopt }; + } + env->Reference_IsUndefined(resultRef, &isUndefined); + if (isUndefined) { + return { true, nullopt }; + } + + ani_double resultRefRes; + if (ANI_OK != env->Object_CallMethodByName_Double( + static_cast(resultRef), "doubleValue", nullptr, &resultRefRes)) { + return { false, nullopt }; + } + double result = static_cast(resultRefRes); + return { true, make_optional(result) }; +} + +tuple>> ParseArrayString(ani_env *env, ani_object obj, string tag) +{ + ani_boolean isUndefined; + ani_ref resultRef; + vector strings; + if (ANI_OK != env->Object_GetPropertyByName_Ref(obj, tag.c_str(), &resultRef)) { + return { false, nullopt }; + } + env->Reference_IsUndefined(resultRef, &isUndefined); + if (isUndefined) { + return { true, nullopt }; + } + + ani_double length; + if (ANI_OK != env->Object_GetPropertyByName_Double( + static_cast(resultRef), "length", &length) || length == 0) { + return { false, nullopt }; + } + auto getterDesc = BuiltInTypes::Array::getterDesc.c_str(); + auto getterSig = BuiltInTypes::Array::objectGetterSig.c_str(); + for (int i = 0; i < int(length); i++) { + ani_ref stringEntryRef; + if (ANI_OK != env->Object_CallMethodByName_Ref( + static_cast(resultRef), getterDesc, getterSig, &stringEntryRef, (ani_int)i)) { + return { false, nullopt }; + } + auto [succ, tmp] = TypeConverter::ToUTF8String(env, static_cast(stringEntryRef)); + if (!succ) { + return { false, nullopt }; + } + strings.emplace_back(tmp); + } + return { true, make_optional>(move(strings)) }; +} + +tuple> ParseFilter(ani_env *env, ani_object obj) +{ + FsFileFilter filter; + + auto [succfileSizeOver, fileSizeOver] = ParseIntParam(env, obj, "fileSizeOver"); + if (!succfileSizeOver) { + HILOGE("Illegal option.fileSizeOver parameter"); + return { false, move(filter) }; + } + filter.SetFileSizeOver(fileSizeOver); + + auto [succlastModifiedAfter, lastModifiedAfter] = ParseDoubleParam(env, obj, "lastModifiedAfter"); + if (!succlastModifiedAfter) { + HILOGE("Illegal option.lastModifiedAfter parameter"); + return { false, move(filter) }; + } + filter.SetLastModifiedAfter(lastModifiedAfter); + + auto [succSuffix, suffix] = ParseArrayString(env, obj, "suffix"); + if (!succSuffix) { + HILOGE("Illegal option.suffix parameter"); + return { false, move(filter) }; + } + filter.SetSuffix(move(suffix)); + + auto [succDisplayName, displayName] = ParseArrayString(env, obj, "displayName"); + if (!succDisplayName) { + HILOGE("Illegal option.displayName parameter"); + return { false, move(filter) }; + } + filter.SetDisplayName(move(displayName)); + + return { true, move(filter) }; +} + +tuple> ParseArgs(ani_env *env, ani_object obj) +{ + FsListFileOptions result; + ani_boolean isUndefined; + env->Reference_IsUndefined(obj, &isUndefined); + if (isUndefined) { + return { true, nullopt }; + } + + auto [succRecursion, recursion] = ParseBooleanParam(env, obj, "recursion"); + if (!succRecursion) { + HILOGE("Invalid recursion"); + return { false, nullopt }; + } + result.recursion = recursion; + + auto [succlistNum, listNumRes] = ParseIntParam(env, obj, "listNum"); + if (!succlistNum) { + HILOGE("Invalid listNum"); + return { false, nullopt }; + } + result.listNum = (int)listNumRes; + + ani_ref filterRef; + if (ANI_OK != env->Object_GetPropertyByName_Ref(obj, "filter", &filterRef)) { + HILOGE("Invalid filter"); + return { false, nullopt }; + } + env->Reference_IsUndefined(filterRef, &isUndefined); + if (isUndefined) { + return { true, make_optional(result) }; + } + auto [succFilter, filterFilterClass] = ParseFilter(env, static_cast(filterRef)); + if (!succFilter) { + HILOGE("Invalid filter"); + return { false, nullopt }; + } + result.filter = move(filterFilterClass); + + return { true, make_optional(result) }; +} + +ani_array_ref ListFileAni::ListFileSync(ani_env *env, [[maybe_unused]] ani_class clazz, ani_string path, ani_object obj) +{ + auto [succPath, srcPath] = TypeConverter::ToUTF8String(env, path); + if (!succPath) { + HILOGE("Invalid path"); + ErrorHandler::Throw(env, EINVAL); + return nullptr; + } + + auto [succOpt, opt] = ParseArgs(env, obj); + if (!succOpt) { + HILOGE("Invalid options Arguments"); + ErrorHandler::Throw(env, EINVAL); + return nullptr; + } + + auto ret = ListFileCore::DoListFile(srcPath, opt); + if (!ret.IsSuccess()) { + HILOGE("DoListFile failed"); + const auto &err = ret.GetError(); + ErrorHandler::Throw(env, err); + return nullptr; + } + + auto fileList = ret.GetData().value(); + const std::string *strArray = fileList.data(); + auto [succ, result] = TypeConverter::ToAniStringList(env, strArray, fileList.size()); + if (!succ) { + HILOGE("Convert list file result to ani string array failed"); + ErrorHandler::Throw(env, UNKNOWN_ERR); + return nullptr; + } + return result; +} + +} // namespace ANI +} // namespace ModuleFileIO +} // namespace FileManagement +} // namespace OHOS \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fs/properties/ani/listfile_ani.h b/interfaces/kits/js/src/mod_fs/properties/ani/listfile_ani.h new file mode 100644 index 0000000000000000000000000000000000000000..1c238ab59f56827e0c7fc571d2d908f78e379540 --- /dev/null +++ b/interfaces/kits/js/src/mod_fs/properties/ani/listfile_ani.h @@ -0,0 +1,36 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef INTERFACES_KITS_JS_SRC_MOD_FS_PROPERTIES_ANI_LISTFILE_ANI_H +#define INTERFACES_KITS_JS_SRC_MOD_FS_PROPERTIES_ANI_LISTFILE_ANI_H + +#include + +namespace OHOS { +namespace FileManagement { +namespace ModuleFileIO { +namespace ANI { + +class ListFileAni final { +public: + static ani_array_ref ListFileSync(ani_env *env, [[maybe_unused]] ani_class clazz, ani_string path, ani_object obj); +}; + +} // namespace ANI +} // namespace ModuleFileIO +} // namespace FileManagement +} // namespace OHOS + +#endif // INTERFACES_KITS_JS_SRC_MOD_FS_PROPERTIES_ANI_LISTFILE_ANI_H \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fs/properties/ani/mkdir_ani.cpp b/interfaces/kits/js/src/mod_fs/properties/ani/mkdir_ani.cpp new file mode 100644 index 0000000000000000000000000000000000000000..2a9b29bcf03347e7759354a5829d21f4711d6c0b --- /dev/null +++ b/interfaces/kits/js/src/mod_fs/properties/ani/mkdir_ani.cpp @@ -0,0 +1,67 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "mkdir_ani.h" + +#include "error_handler.h" +#include "filemgmt_libhilog.h" +#include "mkdir_core.h" +#include "type_converter.h" + +namespace OHOS { +namespace FileManagement { +namespace ModuleFileIO { +namespace ANI { + +void MkdirkAni::MkdirSync0(ani_env *env, [[maybe_unused]] ani_class clazz, ani_string path) +{ + auto [succ, pathStr] = TypeConverter::ToUTF8String(env, path); + if (!succ) { + HILOGE("Invalid path"); + ErrorHandler::Throw(env, EINVAL); + return; + } + + auto ret = MkdirCore::DoMkdir(pathStr); + if (!ret.IsSuccess()) { + HILOGE("Mkdir failed"); + const auto &err = ret.GetError(); + ErrorHandler::Throw(env, err); + return; + } +} + +void MkdirkAni::MkdirSync1(ani_env *env, [[maybe_unused]] ani_class clazz, ani_string path, ani_boolean recursion) +{ + auto [succ, pathStr] = ANI::TypeConverter::ToUTF8String(env, path); + if (!succ) { + HILOGE("Invalid path"); + ErrorHandler::Throw(env, EINVAL); + return; + } + + auto ret = MkdirCore::DoMkdir(pathStr, recursion); + if (!ret.IsSuccess()) { + HILOGE("DoMkdir failed"); + const auto &err = ret.GetError(); + ErrorHandler::Throw(env, err); + return; + } +} + +} // namespace ANI +} // namespace ModuleFileIO +} // namespace FileManagement +} // namespace OHOS diff --git a/interfaces/kits/js/src/mod_fs/properties/ani/mkdir_ani.h b/interfaces/kits/js/src/mod_fs/properties/ani/mkdir_ani.h new file mode 100644 index 0000000000000000000000000000000000000000..195d0db0014c47ddacfe206b4838b47e8388b135 --- /dev/null +++ b/interfaces/kits/js/src/mod_fs/properties/ani/mkdir_ani.h @@ -0,0 +1,37 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef INTERFACES_KITS_JS_SRC_MOD_FS_PROPERTIES_ANI_MKDIR_ANI_H +#define INTERFACES_KITS_JS_SRC_MOD_FS_PROPERTIES_ANI_MKDIR_ANI_H + +#include + +namespace OHOS { +namespace FileManagement { +namespace ModuleFileIO { +namespace ANI { + +class MkdirkAni final { +public: + static void MkdirSync0(ani_env *env, [[maybe_unused]] ani_class clazz, ani_string path); + static void MkdirSync1(ani_env *env, [[maybe_unused]] ani_class clazz, ani_string path, ani_boolean recursion); +}; + +} // namespace ANI +} // namespace ModuleFileIO +} // namespace FileManagement +} // namespace OHOS + +#endif // INTERFACES_KITS_JS_SRC_MOD_FS_PROPERTIES_ANI_MKDIR_ANI_H diff --git a/interfaces/kits/js/src/mod_fs/properties/ani/move_ani.cpp b/interfaces/kits/js/src/mod_fs/properties/ani/move_ani.cpp new file mode 100644 index 0000000000000000000000000000000000000000..3243554f5f9611e115048faacc029838fde49961 --- /dev/null +++ b/interfaces/kits/js/src/mod_fs/properties/ani/move_ani.cpp @@ -0,0 +1,60 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "move_ani.h" + +#include "error_handler.h" +#include "filemgmt_libhilog.h" +#include "move_core.h" +#include "type_converter.h" + +namespace OHOS { +namespace FileManagement { +namespace ModuleFileIO { +namespace ANI { + +void MoveAni::MoveFileSync( + ani_env *env, [[maybe_unused]] ani_class clazz, ani_string src, ani_string dest, ani_object mode) +{ + auto [succSrc, srcPath] = TypeConverter::ToUTF8String(env, src); + if (!succSrc) { + HILOGE("Invalid src"); + ErrorHandler::Throw(env, EINVAL); + return; + } + auto [succDest, destPath] = TypeConverter::ToUTF8String(env, dest); + if (!succDest) { + HILOGE("Invalid dest"); + ErrorHandler::Throw(env, EINVAL); + return; + } + auto [succMode, modeOp] = TypeConverter::ToOptionalInt32(env, mode); + if (!succMode) { + HILOGE("Invalid mode"); + ErrorHandler::Throw(env, EINVAL); + return; + } + auto ret = MoveCore::DoMove(srcPath, destPath, modeOp); + if (!ret.IsSuccess()) { + HILOGE("Move failed"); + const auto &err = ret.GetError(); + ErrorHandler::Throw(env, err); + return; + } +} +} // namespace ANI +} // namespace ModuleFileIO +} // namespace FileManagement +} // namespace OHOS \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fs/properties/ani/move_ani.h b/interfaces/kits/js/src/mod_fs/properties/ani/move_ani.h new file mode 100644 index 0000000000000000000000000000000000000000..e42aa4ac03ef77c6a7a63b41ad807ee846aca483 --- /dev/null +++ b/interfaces/kits/js/src/mod_fs/properties/ani/move_ani.h @@ -0,0 +1,37 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef INTERFACES_KITS_JS_SRC_MOD_FS_PROPERTIES_ANI_MOVE_ANI_H +#define INTERFACES_KITS_JS_SRC_MOD_FS_PROPERTIES_ANI_MOVE_ANI_H + +#include + +namespace OHOS { +namespace FileManagement { +namespace ModuleFileIO { +namespace ANI { + +class MoveAni final { +public: + static void MoveFileSync( + ani_env *env, [[maybe_unused]] ani_class clazz, ani_string src, ani_string dest, ani_object mode); +}; + +} // namespace ANI +} // namespace ModuleFileIO +} // namespace FileManagement +} // namespace OHOS + +#endif // INTERFACES_KITS_JS_SRC_MOD_FS_PROPERTIES_ANI_MOVE_ANI_H \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fs/properties/ani/open_ani.cpp b/interfaces/kits/js/src/mod_fs/properties/ani/open_ani.cpp new file mode 100644 index 0000000000000000000000000000000000000000..3a4049c073bea66166c8056c47c04d6bed76ef08 --- /dev/null +++ b/interfaces/kits/js/src/mod_fs/properties/ani/open_ani.cpp @@ -0,0 +1,69 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "open_ani.h" + +#include "ani_helper.h" +#include "error_handler.h" +#include "file_wrapper.h" +#include "filemgmt_libhilog.h" +#include "open_core.h" +#include "type_converter.h" + +namespace OHOS { +namespace FileManagement { +namespace ModuleFileIO { +namespace ANI { +using namespace OHOS::FileManagement::ModuleFileIO; + +ani_object OpenAni::OpenSync(ani_env *env, [[maybe_unused]] ani_class clazz, ani_string path, ani_object mode) +{ +#ifdef FILE_API_TRACE + HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); +#endif + auto [succPath, filePath] = TypeConverter::ToUTF8String(env, path); + if (!succPath) { + HILOGE("Invalid path"); + ErrorHandler::Throw(env, EINVAL); + return nullptr; + } + + auto [succMode, modeOp] = TypeConverter::ToOptionalInt32(env, mode); + if (!succMode) { + HILOGE("Invalid mode"); + ErrorHandler::Throw(env, EINVAL); + return nullptr; + } + FsResult ret = OpenCore::DoOpen(filePath, modeOp); + if (!ret.IsSuccess()) { + HILOGE("Open failed"); + const auto &err = ret.GetError(); + ErrorHandler::Throw(env, err); + return nullptr; + } + const FsFile *file = ret.GetData().value(); + auto result = FileWrapper::Wrap(env, move(file)); + if (result == nullptr) { + delete file; + file = nullptr; + ErrorHandler::Throw(env, UNKNOWN_ERR); + return nullptr; + } + return result; +} +} // namespace ANI +} // namespace ModuleFileIO +} // namespace FileManagement +} // namespace OHOS \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fs/properties/ani/open_ani.h b/interfaces/kits/js/src/mod_fs/properties/ani/open_ani.h new file mode 100644 index 0000000000000000000000000000000000000000..6c4cda272b34f4d0a4bacb28ba0a74040175e2f8 --- /dev/null +++ b/interfaces/kits/js/src/mod_fs/properties/ani/open_ani.h @@ -0,0 +1,36 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef INTERFACES_KITS_JS_SRC_MOD_FS_PROPERTIES_ANI_OPEN_ANI_H +#define INTERFACES_KITS_JS_SRC_MOD_FS_PROPERTIES_ANI_OPEN_ANI_H + +#include + +namespace OHOS { +namespace FileManagement { +namespace ModuleFileIO { +namespace ANI { + +class OpenAni final { +public: + static ani_object OpenSync(ani_env *env, [[maybe_unused]] ani_class clazz, ani_string path, ani_object mode); +}; + +} // namespace ANI +} // namespace ModuleFileIO +} // namespace FileManagement +} // namespace OHOS + +#endif // INTERFACES_KITS_JS_SRC_MOD_FS_PROPERTIES_ANI_OPEN_ANI_H \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fs/properties/ani/read_ani.cpp b/interfaces/kits/js/src/mod_fs/properties/ani/read_ani.cpp new file mode 100644 index 0000000000000000000000000000000000000000..fa5ce2334a35ed1d5973284dea9a9e1eafd42d22 --- /dev/null +++ b/interfaces/kits/js/src/mod_fs/properties/ani/read_ani.cpp @@ -0,0 +1,81 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "read_ani.h" + +#include +#include "ani_helper.h" +#include "error_handler.h" +#include "filemgmt_libhilog.h" +#include "read_core.h" +#include "type_converter.h" + +namespace OHOS::FileManagement::ModuleFileIO::ANI { + +using namespace std; +using namespace OHOS::FileManagement::ModuleFileIO; + +static tuple> ToReadOptions(ani_env *env, ani_object obj) +{ + ReadOptions options; + ani_boolean isUndefined; + env->Reference_IsUndefined(obj, &isUndefined); + if (isUndefined) { + return { true, nullopt }; + } + + auto [succOffset, offset] = AniHelper::ParseInt64Option(env, obj, "offset"); + if (!succOffset) { + HILOGE("Illegal option.offset parameter"); + return { false, nullopt }; + } + options.offset = offset; + + auto [succLength, length] = AniHelper::ParseInt64Option(env, obj, "length"); + if (!succLength) { + HILOGE("Illegal option.length parameter"); + return { false, nullopt }; + } + options.length = length; + return { true, make_optional(move(options)) }; +} + +ani_double ReadAni::ReadSync( + ani_env *env, [[maybe_unused]] ani_class clazz, ani_double fd, ani_arraybuffer buffer, ani_object options) +{ + auto [succBuf, arrayBuffer] = TypeConverter::ToArrayBuffer(env, buffer); + if (!succBuf) { + HILOGE("Failed to resolve arrayBuffer!"); + ErrorHandler::Throw(env, EINVAL); + return -1; + } + + auto [succOp, op] = ToReadOptions(env, options); + if (!succOp) { + HILOGE("Failed to resolve options!"); + ErrorHandler::Throw(env, EINVAL); + return -1; + } + + auto ret = ReadCore::DoRead(static_cast(fd), arrayBuffer, op); + if (!ret.IsSuccess()) { + HILOGE("Read file content failed!"); + const auto &err = ret.GetError(); + ErrorHandler::Throw(env, err); + return -1; + } + return static_cast(ret.GetData().value()); +} +} // namespace OHOS::FileManagement::ModuleFileIO::ANI \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fs/properties/ani/read_ani.h b/interfaces/kits/js/src/mod_fs/properties/ani/read_ani.h new file mode 100644 index 0000000000000000000000000000000000000000..2f18a20f3f3792b40d0618e0f72c6657ceda2755 --- /dev/null +++ b/interfaces/kits/js/src/mod_fs/properties/ani/read_ani.h @@ -0,0 +1,30 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef INTERFACES_KITS_JS_SRC_MOD_FS_PROPERTIES_ANI_READ_ANI_H +#define INTERFACES_KITS_JS_SRC_MOD_FS_PROPERTIES_ANI_READ_ANI_H + +#include + +namespace OHOS::FileManagement::ModuleFileIO::ANI { + +class ReadAni final { +public: + static ani_double ReadSync( + ani_env *env, [[maybe_unused]] ani_class clazz, ani_double fd, ani_arraybuffer buffer, ani_object options); +}; + +} // namespace OHOS::FileManagement::ModuleFileIO::ANI +#endif // INTERFACES_KITS_JS_SRC_MOD_FS_PROPERTIES_ANI_READ_ANI_H \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fs/properties/ani/read_text_ani.cpp b/interfaces/kits/js/src/mod_fs/properties/ani/read_text_ani.cpp new file mode 100644 index 0000000000000000000000000000000000000000..05689d3d79dd010dc42ea4374d4648e08a78b358 --- /dev/null +++ b/interfaces/kits/js/src/mod_fs/properties/ani/read_text_ani.cpp @@ -0,0 +1,108 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "read_text_ani.h" + +#include +#include "ani_helper.h" +#include "error_handler.h" +#include "filemgmt_libhilog.h" +#include "read_text_core.h" +#include "type_converter.h" + +namespace OHOS { +namespace FileManagement { +namespace ModuleFileIO { +namespace ANI { + +using namespace std; +using namespace OHOS::FileManagement::ModuleFileIO; +using namespace OHOS::FileManagement::ModuleFileIO::ANI; + +static tuple> ToReadTextOptions(ani_env *env, ani_object obj) +{ + ReadTextOptions options; + + ani_boolean isUndefined; + env->Reference_IsUndefined(obj, &isUndefined); + if (isUndefined) { + return { true, nullopt }; + } + + auto [succOffset, offset] = AniHelper::ParseInt64Option(env, obj, "offset"); + if (!succOffset) { + HILOGE("Illegal option.offset parameter"); + return { false, nullopt }; + } + options.offset = offset; + + auto [succLength, length] = AniHelper::ParseInt64Option(env, obj, "length"); + if (!succLength) { + HILOGE("Illegal option.length parameter"); + return { false, nullopt }; + } + options.length = length; + + auto [succEncoding, encoding] = AniHelper::ParseEncoding(env, obj); + if (!succEncoding) { + HILOGE("Illegal option.encoding parameter"); + return { false, nullopt }; + } + options.encoding = encoding; + + return { true, make_optional(move(options)) }; +} + +ani_string ReadTextAni::ReadTextSync( + ani_env *env, [[maybe_unused]] ani_class clazz, ani_string filePath, ani_object obj) +{ + auto [succOpt, options] = ToReadTextOptions(env, obj); + if (!succOpt) { + HILOGE("Invalid options"); + ErrorHandler::Throw(env, EINVAL); + return nullptr; + } + + auto [succPath, path] = TypeConverter::ToUTF8String(env, filePath); + if (!succPath) { + HILOGE("Invalid Path"); + ErrorHandler::Throw(env, EINVAL); + return nullptr; + } + + auto ret = ReadTextCore::DoReadText(path, options); + if (!ret.IsSuccess()) { + HILOGE("DoReadText failed"); + const auto &err = ret.GetError(); + ErrorHandler::Throw(env, err); + return nullptr; + } + + const auto &resText = ret.GetData().value(); + string res = std::get<0>(resText); // get buffer + size_t size = std::get<1>(resText); // get buffer length + auto [succ, result] = TypeConverter::ToAniString(env, res, size); + if (!succ) { + HILOGE("Convert result to ani string failed"); + ErrorHandler::Throw(env, UNKNOWN_ERR); + return nullptr; + } + return result; +} + +} // namespace ANI +} // namespace ModuleFileIO +} // namespace FileManagement +} // namespace OHOS \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fs/properties/ani/read_text_ani.h b/interfaces/kits/js/src/mod_fs/properties/ani/read_text_ani.h new file mode 100644 index 0000000000000000000000000000000000000000..4356eb7b16fa9b8de1330c3df9c1c49a913c573c --- /dev/null +++ b/interfaces/kits/js/src/mod_fs/properties/ani/read_text_ani.h @@ -0,0 +1,36 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef INTERFACES_KITS_JS_SRC_MOD_FS_PROPERTIES_ANI_READ_TEXT_ANI_H +#define INTERFACES_KITS_JS_SRC_MOD_FS_PROPERTIES_ANI_READ_TEXT_ANI_H + +#include + +namespace OHOS { +namespace FileManagement { +namespace ModuleFileIO { +namespace ANI { + +class ReadTextAni final { +public: + static ani_string ReadTextSync(ani_env *env, [[maybe_unused]] ani_class clazz, ani_string filePath, ani_object obj); +}; + +} // namespace ANI +} // namespace ModuleFileIO +} // namespace FileManagement +} // namespace OHOS + +#endif // INTERFACES_KITS_JS_SRC_MOD_FS_PROPERTIES_ANI_READ_TEXT_ANI_H \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fs/properties/ani/rmdir_ani.cpp b/interfaces/kits/js/src/mod_fs/properties/ani/rmdir_ani.cpp new file mode 100644 index 0000000000000000000000000000000000000000..04a4cfa6b2fd2ab944f40b5eb02c1e02b630f4e3 --- /dev/null +++ b/interfaces/kits/js/src/mod_fs/properties/ani/rmdir_ani.cpp @@ -0,0 +1,49 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "rmdir_ani.h" + +#include "error_handler.h" +#include "filemgmt_libhilog.h" +#include "rmdir_core.h" +#include "type_converter.h" + +namespace OHOS { +namespace FileManagement { +namespace ModuleFileIO { +namespace ANI { +using namespace std; + +void RmdirAni::RmdirSync(ani_env *env, [[maybe_unused]] ani_class clazz, ani_string path) +{ + auto [succPath, pathStr] = TypeConverter::ToUTF8String(env, path); + if (!succPath) { + HILOGE("Invalid path"); + ErrorHandler::Throw(env, EINVAL); + return; + } + auto ret = RmdirentCore::DoRmdirent(pathStr); + if (!ret.IsSuccess()) { + HILOGE("DoRmdirent failed"); + const auto &err = ret.GetError(); + ErrorHandler::Throw(env, err); + return; + } +} + +} // namespace ANI +} // namespace ModuleFileIO +} // namespace FileManagement +} // namespace OHOS \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fs/properties/ani/rmdir_ani.h b/interfaces/kits/js/src/mod_fs/properties/ani/rmdir_ani.h new file mode 100644 index 0000000000000000000000000000000000000000..dcb5c41484526b531d282fa805e804cdd62ea7e1 --- /dev/null +++ b/interfaces/kits/js/src/mod_fs/properties/ani/rmdir_ani.h @@ -0,0 +1,36 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef INTERFACES_KITS_JS_SRC_MOD_FS_PROPERTIES_ANI_RMDIR_ANI_H +#define INTERFACES_KITS_JS_SRC_MOD_FS_PROPERTIES_ANI_RMDIR_ANI_H + +#include + +namespace OHOS { +namespace FileManagement { +namespace ModuleFileIO { +namespace ANI { + +class RmdirAni final { +public: + static void RmdirSync(ani_env *env, [[maybe_unused]] ani_class clazz, ani_string path); +}; + +} // namespace ANI +} // namespace ModuleFileIO +} // namespace FileManagement +} // namespace OHOS + +#endif // INTERFACES_KITS_JS_SRC_MOD_FS_PROPERTIES_ANI_RMDIR_ANI_H \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fs/properties/ani/truncate_ani.cpp b/interfaces/kits/js/src/mod_fs/properties/ani/truncate_ani.cpp new file mode 100644 index 0000000000000000000000000000000000000000..6176d45e123c92a84e679d4b6ccce0bc7f6fc9e3 --- /dev/null +++ b/interfaces/kits/js/src/mod_fs/properties/ani/truncate_ani.cpp @@ -0,0 +1,57 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "truncate_ani.h" + +#include "error_handler.h" +#include "file_utils.h" +#include "filemgmt_libhilog.h" +#include "truncate_core.h" +#include "type_converter.h" + +namespace OHOS { +namespace FileManagement { +namespace ModuleFileIO { +namespace ANI { + +void TruncateAni::TruncateSync(ani_env *env, [[maybe_unused]] ani_class clazz, ani_object file, ani_object length) +{ + auto [succ, fileinfo] = TypeConverter::ToFileInfo(env, file); + if (!succ) { + HILOGE("Invalid fd/path"); + ErrorHandler::Throw(env, EINVAL); + return; + } + + auto [succLen, len] = TypeConverter::ToOptionalInt64(env, length); + if (!succLen) { + HILOGE("Invalid truncate length"); + ErrorHandler::Throw(env, EINVAL); + return; + } + + auto ret = TruncateCore::DoTruncate(fileinfo, len); + if (!ret.IsSuccess()) { + HILOGE("Truncate failed"); + const auto &err = ret.GetError(); + ErrorHandler::Throw(env, err); + return; + } +} + +} // namespace ANI +} // namespace ModuleFileIO +} // namespace FileManagement +} // namespace OHOS \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fs/properties/ani/truncate_ani.h b/interfaces/kits/js/src/mod_fs/properties/ani/truncate_ani.h new file mode 100644 index 0000000000000000000000000000000000000000..ccdbe5e574cda8a974f972c854d15ae29b251409 --- /dev/null +++ b/interfaces/kits/js/src/mod_fs/properties/ani/truncate_ani.h @@ -0,0 +1,36 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef INTERFACES_KITS_JS_SRC_MOD_FS_PROPERTIES_ANI_TRUNCATE_ANI_H +#define INTERFACES_KITS_JS_SRC_MOD_FS_PROPERTIES_ANI_TRUNCATE_ANI_H + +#include + +namespace OHOS { +namespace FileManagement { +namespace ModuleFileIO { +namespace ANI { + +class TruncateAni final { +public: + static void TruncateSync(ani_env *env, [[maybe_unused]] ani_class clazz, ani_object file, ani_object length); +}; + +} // namespace ANI +} // namespace ModuleFileIO +} // namespace FileManagement +} // namespace OHOS + +#endif // INTERFACES_KITS_JS_SRC_MOD_FS_PROPERTIES_ANI_TRUNCATE_ANI_H \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fs/properties/ani/unlink_ani.cpp b/interfaces/kits/js/src/mod_fs/properties/ani/unlink_ani.cpp new file mode 100644 index 0000000000000000000000000000000000000000..763d6e72ed69c93edc91c7831a914408ab7e77d2 --- /dev/null +++ b/interfaces/kits/js/src/mod_fs/properties/ani/unlink_ani.cpp @@ -0,0 +1,48 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "unlink_ani.h" + +#include "error_handler.h" +#include "filemgmt_libhilog.h" +#include "type_converter.h" +#include "unlink_core.h" + +namespace OHOS { +namespace FileManagement { +namespace ModuleFileIO { +namespace ANI { + +void UnlinkAni::UnlinkSync(ani_env *env, [[maybe_unused]] ani_class clazz, ani_string path) +{ + auto [succ, pathStr] = TypeConverter::ToUTF8String(env, path); + if (!succ) { + HILOGE("Invalid path from ETS first argument"); + ErrorHandler::Throw(env, EINVAL); + return; + } + auto ret = UnlinkCore::DoUnlink(pathStr); + if (!ret.IsSuccess()) { + HILOGE("Unlink failed"); + const auto &err = ret.GetError(); + ErrorHandler::Throw(env, err); + return; + } +} + +} // namespace ANI +} // namespace ModuleFileIO +} // namespace FileManagement +} // namespace OHOS \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fs/properties/ani/unlink_ani.h b/interfaces/kits/js/src/mod_fs/properties/ani/unlink_ani.h new file mode 100644 index 0000000000000000000000000000000000000000..64aee8bd1952c4da7d0ef61922f219da98ddb62f --- /dev/null +++ b/interfaces/kits/js/src/mod_fs/properties/ani/unlink_ani.h @@ -0,0 +1,36 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef INTERFACES_KITS_JS_SRC_MOD_FS_PROPERTIES_ANI_UNLINK_ANI_H +#define INTERFACES_KITS_JS_SRC_MOD_FS_PROPERTIES_ANI_UNLINK_ANI_H + +#include + +namespace OHOS { +namespace FileManagement { +namespace ModuleFileIO { +namespace ANI { + +class UnlinkAni final { +public: + static void UnlinkSync(ani_env *env, [[maybe_unused]] ani_class clazz, ani_string path); +}; + +} // namespace ANI +} // namespace ModuleFileIO +} // namespace FileManagement +} // namespace OHOS + +#endif // INTERFACES_KITS_JS_SRC_MOD_FS_PROPERTIES_ANI_UNLINK_ANI_H \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fs/properties/ani/write_ani.cpp b/interfaces/kits/js/src/mod_fs/properties/ani/write_ani.cpp new file mode 100644 index 0000000000000000000000000000000000000000..6c718e07944974f667bf5250d8ab3d9d3ca72de0 --- /dev/null +++ b/interfaces/kits/js/src/mod_fs/properties/ani/write_ani.cpp @@ -0,0 +1,149 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "write_ani.h" + +#include +#include "ani_helper.h" +#include "ani_signature.h" +#include "error_handler.h" +#include "filemgmt_libhilog.h" +#include "type_converter.h" +#include "write_core.h" + +namespace OHOS { +namespace FileManagement { +namespace ModuleFileIO { +namespace ANI { +using namespace std; +using namespace OHOS::FileManagement::ModuleFileIO; +using namespace OHOS::FileManagement::ModuleFileIO::ANI::AniSignature; + +static tuple> ToWriteOptions(ani_env *env, ani_object obj) +{ + WriteOptions options; + ani_boolean isUndefined; + env->Reference_IsUndefined(obj, &isUndefined); + if (isUndefined) { + return { true, nullopt }; + } + + auto [succEncoding, encoding] = AniHelper::ParseEncoding(env, obj); + if (!succEncoding) { + HILOGE("Illegal option.encoding parameter"); + return { false, nullopt }; + } + options.encoding = encoding; + + auto [succOffset, offset] = AniHelper::ParseInt64Option(env, obj, "offset"); + if (!succOffset) { + HILOGE("Illegal option.offset parameter"); + return { false, nullopt }; + } + options.offset = offset; + + auto [succLength, length] = AniHelper::ParseInt64Option(env, obj, "length"); + if (!succLength) { + HILOGE("Illegal option.length parameter"); + return { false, nullopt }; + } + options.length = length; + + return { true, make_optional(move(options)) }; +} + +static std::tuple ParseStringBuffer(ani_env *env, const ani_object &buf) +{ + auto classDesc = BuiltInTypes::String::classDesc.c_str(); + ani_class cls; + env->FindClass(classDesc, &cls); + + ani_boolean isString; + env->Object_InstanceOf(buf, cls, &isString); + if (!isString) { + return { false, {} }; + } + auto result = static_cast(buf); + return { true, std::move(result) }; +} + +static std::tuple ParseArrayBuffer(ani_env *env, const ani_object &buf) +{ + auto classDesc = BuiltInTypes::ArrayBuffer::classDesc.c_str(); + ani_class cls; + env->FindClass(classDesc, &cls); + + ani_boolean isArrayBuffer; + env->Object_InstanceOf(buf, cls, &isArrayBuffer); + if (!isArrayBuffer) { + return { false, {} }; + } + auto result = static_cast(buf); + return { true, std::move(result) }; +} + +ani_double WriteAni::WriteSync( + ani_env *env, [[maybe_unused]] ani_class clazz, ani_double fd, ani_object buf, ani_object options) +{ + auto [succOp, op] = ToWriteOptions(env, options); + if (!succOp) { + HILOGE("Failed to resolve options!"); + ErrorHandler::Throw(env, EINVAL); + return -1; + } + + auto [isString, stringBuffer] = ParseStringBuffer(env, buf); + if (isString) { + auto [succBuf, buffer] = TypeConverter::ToUTF8String(env, stringBuffer); + if (!succBuf) { + HILOGE("Failed to resolve stringBuffer!"); + ErrorHandler::Throw(env, EINVAL); + return -1; + } + auto ret = WriteCore::DoWrite(static_cast(fd), buffer, op); + if (!ret.IsSuccess()) { + HILOGE("write buffer failed!"); + const auto &err = ret.GetError(); + ErrorHandler::Throw(env, err); + return -1; + } + return static_cast(ret.GetData().value()); + } + + auto [isArrayBuffer, arrayBuffer] = ParseArrayBuffer(env, buf); + if (isArrayBuffer) { + auto [succBuf, buffer] = TypeConverter::ToArrayBuffer(env, arrayBuffer); + if (!succBuf) { + HILOGE("Failed to resolve arrayBuffer!"); + ErrorHandler::Throw(env, EINVAL); + return -1; + } + auto ret = WriteCore::DoWrite(static_cast(fd), buffer, op); + if (!ret.IsSuccess()) { + HILOGE("write buffer failed!"); + const auto &err = ret.GetError(); + ErrorHandler::Throw(env, err); + return -1; + } + return static_cast(ret.GetData().value()); + } + HILOGE("Unsupported buffer type!"); + ErrorHandler::Throw(env, EINVAL); + return -1; +} +} // namespace ANI +} // namespace ModuleFileIO +} // namespace FileManagement +} // namespace OHOS \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fs/properties/ani/write_ani.h b/interfaces/kits/js/src/mod_fs/properties/ani/write_ani.h new file mode 100644 index 0000000000000000000000000000000000000000..2ac1c8d703dc3f3184dada321983ace9e45196fe --- /dev/null +++ b/interfaces/kits/js/src/mod_fs/properties/ani/write_ani.h @@ -0,0 +1,37 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef INTERFACES_KITS_JS_SRC_MOD_FS_PROPERTIES_ANI_WRITE_ANI_H +#define INTERFACES_KITS_JS_SRC_MOD_FS_PROPERTIES_ANI_WRITE_ANI_H + +#include + +namespace OHOS { +namespace FileManagement { +namespace ModuleFileIO { +namespace ANI { + +class WriteAni final { +public: + static ani_double WriteSync( + ani_env *env, [[maybe_unused]] ani_class clazz, ani_double fd, ani_object buf, ani_object options); +}; + +} // namespace ANI +} // namespace ModuleFileIO +} // namespace FileManagement +} // namespace OHOS + +#endif // INTERFACES_KITS_JS_SRC_MOD_FS_PROPERTIES_ANI_WRITE_ANI_H \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fs/properties/close_core.cpp b/interfaces/kits/js/src/mod_fs/properties/close_core.cpp new file mode 100644 index 0000000000000000000000000000000000000000..fc6e084f57638f4be3dcfa62f01a2f0d0f7d50a8 --- /dev/null +++ b/interfaces/kits/js/src/mod_fs/properties/close_core.cpp @@ -0,0 +1,81 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "close_core.h" + +#include +#include +#include + +#include "file_utils.h" +#include "filemgmt_libhilog.h" + +namespace OHOS::FileManagement::ModuleFileIO { +using namespace std; + +static int32_t CloseFd(int fd) +{ + unique_ptr closeReq = { new uv_fs_t, FsUtils::FsReqCleanup }; + if (!closeReq) { + HILOGE("Failed to request heap memory."); + return ENOMEM; + } + int ret = uv_fs_close(nullptr, closeReq.get(), fd, nullptr); + if (ret < 0) { + HILOGE("Failed to close file with ret: %{public}d", ret); + return ret; + } + return ERRNO_NOERR; +} + +static bool ValidFd(const int32_t &fd) +{ + if (fd < 0) { + HILOGE("Invalid fd"); + return false; + } + return true; +} + +FsResult CloseCore::DoClose(const int32_t &fd) +{ + if (!ValidFd(fd)) { + return FsResult::Error(EINVAL); + } + auto err = CloseFd(fd); + if (err) { + HILOGE("Failed to close fd"); + return FsResult::Error(err); + } + return FsResult::Success(); +} + +FsResult CloseCore::DoClose(FsFile *file) +{ + auto ret = file->GetFD(); + if (!ret.IsSuccess()) { + HILOGE("Failed to get fd"); + return FsResult::Error(EINVAL); + } + auto err = CloseFd(ret.GetData().value()); + if (err) { + HILOGE("Failed to close file"); + return FsResult::Error(err); + } + + file->RemoveEntity(); + return FsResult::Success(); +} +} // namespace OHOS::FileManagement::ModuleFileIO diff --git a/interfaces/kits/js/src/mod_fs/properties/close_core.h b/interfaces/kits/js/src/mod_fs/properties/close_core.h new file mode 100644 index 0000000000000000000000000000000000000000..22acf446683995f36287ffb545bd063ae4d88fbc --- /dev/null +++ b/interfaces/kits/js/src/mod_fs/properties/close_core.h @@ -0,0 +1,34 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef INTERFACES_KITS_JS_SRC_MOD_FS_PROPERTIES_CLOSE_CORE_H +#define INTERFACES_KITS_JS_SRC_MOD_FS_PROPERTIES_CLOSE_CORE_H + +#include "filemgmt_libfs.h" +#include "fs_file.h" +#include "fs_utils.h" +#include "fs_result.h" + +namespace OHOS::FileManagement::ModuleFileIO { + +class CloseCore final { +public: + static FsResult DoClose(const int32_t &fd); + static FsResult DoClose(FsFile *file); +}; + +} // namespace OHOS::FileManagement::ModuleFileIO + +#endif // INTERFACES_KITS_JS_SRC_MOD_FS_PROPERTIES_CLOSE_CORE_H \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fs/properties/copy.cpp b/interfaces/kits/js/src/mod_fs/properties/copy.cpp index b3a8b57168f71dfb06e2add5580449b90c5db46f..be96aeace245a4de940fc8094464a909d941f7a5 100644 --- a/interfaces/kits/js/src/mod_fs/properties/copy.cpp +++ b/interfaces/kits/js/src/mod_fs/properties/copy.cpp @@ -364,6 +364,27 @@ void Copy::CopyComplete(std::shared_ptr infos, std::shared_ptr infos, std::shared_ptr callback) +{ + Storage::DistributedFile::ProcessCallback processListener; + if (infos->hasListener) { + processListener = [infos, callback](uint64_t processSize, uint64_t totalSize) -> void { + callback->progressSize = processSize; + callback->totalSize = totalSize; + OnFileReceive(infos); + }; + } + if (infos->taskSignal != nullptr) { + infos->taskSignal->MarkDfsTask(); + infos->taskSignal->SetCopyTaskUri(infos->srcUri, infos->destUri); + } + LOGI("Copy begin"); + auto result = Storage::DistributedFile::FileCopyManager::GetInstance()->Copy(infos->srcUri, infos->destUri, + processListener); + LOGI("Copy end, result = %{public}d", result); + return result; +} + napi_value Copy::Async(napi_env env, napi_callback_info info) { NFuncArg funcArg(env, info); @@ -379,20 +400,7 @@ napi_value Copy::Async(napi_env env, napi_callback_info info) return nullptr; } auto cbExec = [infos, callback]() -> NError { - std::function processListener = - [infos, callback](uint64_t processSize, uint64_t totalSize) -> void { - callback->progressSize = processSize; - callback->totalSize = totalSize; - OnFileReceive(infos); - }; - if (infos->taskSignal != nullptr) { - infos->taskSignal->MarkDfsTask(); - infos->taskSignal->SetCopyTaskUri(infos->srcUri, infos->destUri); - } - LOGI("Copy begin"); - auto result = Storage::DistributedFile::FileCopyManager::GetInstance()->Copy(infos->srcUri, infos->destUri, - processListener); - LOGI("Copy end, result = %{public}d", result); + auto result = ExecCopy(infos, callback); auto it = softbusErr2ErrCodeTable.find(result); if (it != softbusErr2ErrCodeTable.end()) { result = it->second; diff --git a/interfaces/kits/js/src/mod_fs/properties/copy.h b/interfaces/kits/js/src/mod_fs/properties/copy.h index 417ff264524abdb165a9e02eb8fd435a51babdc3..ecf7b9b047dfadc406585ac858dd9ae19d6273c8 100644 --- a/interfaces/kits/js/src/mod_fs/properties/copy.h +++ b/interfaces/kits/js/src/mod_fs/properties/copy.h @@ -135,7 +135,7 @@ private: static int CopyDirFunc(const string &src, const string &dest, std::shared_ptr infos); static tuple> CreateFileInfos( const std::string &srcUri, const std::string &destUri, NVal &listener, NVal copySignal); - static int ExecCopy(std::shared_ptr infos); + static int32_t ExecCopy(std::shared_ptr infos, std::shared_ptr callback); // operator of file size static int UpdateProgressSize(const std::string &filePath, diff --git a/interfaces/kits/js/src/mod_fs/properties/copy_file_core.cpp b/interfaces/kits/js/src/mod_fs/properties/copy_file_core.cpp new file mode 100644 index 0000000000000000000000000000000000000000..840a547d90cc5c93b204a779bfa9a1af3c33be84 --- /dev/null +++ b/interfaces/kits/js/src/mod_fs/properties/copy_file_core.cpp @@ -0,0 +1,210 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "copy_file_core.h" + +#include +#include +#include +#include +#include +#include + +#include +#include + +#include "file_utils.h" +#include "filemgmt_libhilog.h" + +namespace OHOS::FileManagement::ModuleFileIO { +using namespace std; + +static int32_t IsAllPath(FileInfo &srcFile, FileInfo &destFile) +{ +#if !defined(WIN_PLATFORM) && !defined(IOS_PLATFORM) + filesystem::path srcPath(string(srcFile.path.get())); + filesystem::path dstPath(string(destFile.path.get())); + error_code errCode; + if (!filesystem::copy_file(srcPath, dstPath, filesystem::copy_options::overwrite_existing, + errCode)) { + HILOGE("Failed to copy file, error code: %{public}d", errCode.value()); + return errCode.value(); + } +#else + std::unique_ptr copyfileReq = { + new (nothrow) uv_fs_t, FsUtils::FsReqCleanup}; + if (!copyfileReq) { + HILOGE("Failed to request heap memory."); + return ENOMEM; + } + int ret = uv_fs_copyfile(nullptr, copyfileReq.get(), srcFile.path.get(), destFile.path.get(), + UV_FS_COPYFILE_FICLONE, nullptr); + if (ret < 0) { + HILOGE("Failed to copy file when all parameters are paths"); + return ret; + } +#endif + return ERRNO_NOERR; +} + +static int32_t SendFileCore(FileInfo &srcFdg, FileInfo &destFdg, struct stat &statbf) +{ + std::unique_ptr sendfileReq = { + new (nothrow) uv_fs_t, FsUtils::FsReqCleanup}; + if (!sendfileReq) { + HILOGE("Failed to request heap memory."); + return ENOMEM; + } + int64_t offset = 0; + size_t size = static_cast(statbf.st_size); + int ret = 0; + while (size > 0) { + ret = uv_fs_sendfile(nullptr, sendfileReq.get(), destFdg.fdg->GetFD(), srcFdg.fdg->GetFD(), + offset, std::min(MAX_SIZE, size), nullptr); + if (ret < 0) { + HILOGE("Failed to sendfile by ret : %{public}d", ret); + return ret; + } + if (static_cast(ret) > size) { + HILOGE("More bytes returned than the size of the file. The file size is " + "%{public}zu" + "The bytes returned is %{public}d", + size, ret); + return EIO; + } + offset += static_cast(ret); + size -= static_cast(ret); + if (ret == 0) { + break; + } + } + if (size != 0) { + HILOGE("The execution of the sendfile task was terminated, remaining file " + "size %{public}zu", size); + return EIO; + } + return ERRNO_NOERR; +} + +static int32_t TruncateCore(const FileInfo &fileInfo) +{ + std::unique_ptr ftruncateReq = { + new (nothrow) uv_fs_t, FsUtils::FsReqCleanup}; + if (!ftruncateReq) { + HILOGE("Failed to request heap memory."); + return ENOMEM; + } + int ret = uv_fs_ftruncate(nullptr, ftruncateReq.get(), fileInfo.fdg->GetFD(), 0, nullptr); + if (ret < 0) { + HILOGE("Failed to truncate dstFile with ret: %{public}d", ret); + return ret; + } + return ERRNO_NOERR; +} + +static int32_t OpenCore(FileInfo &fileInfo, const int flags, const int mode) +{ + std::unique_ptr openReq = { + new (nothrow) uv_fs_t, FsUtils::FsReqCleanup}; + if (!openReq) { + HILOGE("Failed to request heap memory."); + return ENOMEM; + } + int ret = uv_fs_open(nullptr, openReq.get(), fileInfo.path.get(), flags, mode, nullptr); + if (ret < 0) { + HILOGE("Failed to open srcFile with ret: %{public}d", ret); + return ret; + } + fileInfo.fdg = CreateUniquePtr(ret, true); + if (fileInfo.fdg == nullptr) { + HILOGE("Failed to request heap memory."); + close(ret); + return ENOMEM; + } + return ERRNO_NOERR; +} + +static int32_t OpenFile(FileInfo &srcFile, FileInfo &destFile) +{ + if (srcFile.isPath) { + auto openResult = OpenCore(srcFile, UV_FS_O_RDONLY, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP); + if (openResult) { + return openResult; + } + } + struct stat statbf; + if (fstat(srcFile.fdg->GetFD(), &statbf) < 0) { + HILOGE("Failed to get stat of file by fd: %{public}d", srcFile.fdg->GetFD()); + return errno; + } + if (destFile.isPath) { + auto openResult = OpenCore(destFile, UV_FS_O_RDWR | UV_FS_O_CREAT | UV_FS_O_TRUNC, + S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP); + if (openResult) { + return openResult; + } + } else { + auto truncateResult = TruncateCore(destFile); + if (truncateResult) { + return truncateResult; + } + auto ret = lseek(destFile.fdg->GetFD(), 0, SEEK_SET); + if (ret < 0) { + HILOGE("Failed to lseek destFile, errno: %{public}d", errno); + return errno; + } + } + if (statbf.st_size == 0) { + return ERRNO_NOERR; + } + return SendFileCore(srcFile, destFile, statbf); +} + +static tuple ValidMode(const optional &mode) +{ + int modeValue = 0; + if (mode.has_value()) { + modeValue = mode.value(); + if (modeValue) { + return { false, modeValue }; + } + } + return { true, modeValue }; +} + +FsResult CopyFileCore::DoCopyFile(FileInfo &src, FileInfo &dest, + const optional &mode) +{ + auto [succMode, modeValue] = ValidMode(mode); + if (!succMode) { + HILOGE("Failed to convert mode to int32"); + return FsResult::Error(EINVAL); + } + + if (src.isPath && dest.isPath) { + auto err = IsAllPath(src, dest); + if (err) { + return FsResult::Error(err); + } + } else { + auto err = OpenFile(src, dest); + if (err) { + return FsResult::Error(err); + } + } + return FsResult::Success(); +} + +} // namespace OHOS::FileManagement::ModuleFileIO \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fs/properties/copy_file_core.h b/interfaces/kits/js/src/mod_fs/properties/copy_file_core.h new file mode 100644 index 0000000000000000000000000000000000000000..2535f5c7572f1332460e7b478fbafc1bb22f5703 --- /dev/null +++ b/interfaces/kits/js/src/mod_fs/properties/copy_file_core.h @@ -0,0 +1,33 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef INTERFACES_KITS_JS_SRC_MOD_FS_PROPERTIES_COPY_FILE_CORE_H +#define INTERFACES_KITS_JS_SRC_MOD_FS_PROPERTIES_COPY_FILE_CORE_H + +#include "filemgmt_libfs.h" +#include "fs_utils.h" + +namespace OHOS::FileManagement::ModuleFileIO { +using namespace std; + +class CopyFileCore final { +public: + static FsResult DoCopyFile(FileInfo &src, FileInfo &dest, + const optional &mode = nullopt); +}; +constexpr size_t MAX_SIZE = 0x7ffff000; + +} // namespace OHOS::FileManagement::ModuleFileIO +#endif // INTERFACES_KITS_JS_SRC_MOD_FS_PROPERTIES_COPY_FILE_CORE_H \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fs/properties/copydir.cpp b/interfaces/kits/js/src/mod_fs/properties/copydir.cpp index 1c643abb8ace3839f7d7dfa64db8a59f5be8ce37..d71ce9c529e791965627d6527cde54605084d7d1 100644 --- a/interfaces/kits/js/src/mod_fs/properties/copydir.cpp +++ b/interfaces/kits/js/src/mod_fs/properties/copydir.cpp @@ -282,6 +282,7 @@ napi_value CopyDir::Sync(napi_env env, napi_callback_info info) NError(ret).ThrowErrAddData(env, EEXIST, PushErrFilesInData(env, errfiles)); return nullptr; } else if (ret) { + HILOGE("Failed to copy dir, ret %{public}d", ret); NError(ret).ThrowErr(env); return nullptr; } diff --git a/interfaces/kits/js/src/mod_fs/properties/fdatasync.cpp b/interfaces/kits/js/src/mod_fs/properties/fdatasync.cpp index c50b0095058e3ca03da7880a6b060ffdab3ca84a..94ace2d8e8b390aafed757acf966bcdaf0bc3849 100644 --- a/interfaces/kits/js/src/mod_fs/properties/fdatasync.cpp +++ b/interfaces/kits/js/src/mod_fs/properties/fdatasync.cpp @@ -86,7 +86,7 @@ napi_value Fdatasync::Async(napi_env env, napi_callback_info info) } int ret = uv_fs_fdatasync(nullptr, fdatasync_req.get(), fd, nullptr); if (ret < 0) { - HILOGE("Failed to transfer data associated with file descriptor: %{public}d", fd); + HILOGE("Failed to transfer data associated with file descriptor: %{public}d, ret %{public}d", fd, ret); return NError(ret); } else { return NError(ERRNO_NOERR); diff --git a/interfaces/kits/js/src/mod_fs/properties/fsync.cpp b/interfaces/kits/js/src/mod_fs/properties/fsync.cpp index ceec9a7e5d5049c6a2de236ca08eb364db9f30f9..85c22577c4f5f0dede36b68c8079f773c835695f 100644 --- a/interfaces/kits/js/src/mod_fs/properties/fsync.cpp +++ b/interfaces/kits/js/src/mod_fs/properties/fsync.cpp @@ -51,7 +51,7 @@ napi_value Fsync::Sync(napi_env env, napi_callback_info info) } int ret = uv_fs_fsync(nullptr, fsync_req.get(), fd, nullptr); if (ret < 0) { - HILOGE("Failed to transfer data associated with file descriptor: %{public}d", fd); + HILOGE("Failed to transfer data associated with file descriptor: %{public}d, ret:%{public}d", fd, ret); NError(ret).ThrowErr(env); return nullptr; } @@ -83,7 +83,7 @@ napi_value Fsync::Async(napi_env env, napi_callback_info info) } int ret = uv_fs_fsync(nullptr, fsync_req.get(), fd, nullptr); if (ret < 0) { - HILOGE("Failed to transfer data associated with file descriptor: %{public}d", fd); + HILOGE("Failed to transfer data associated with file descriptor: %{public}d, ret %{public}d", fd, ret); return NError(ret); } else { return NError(ERRNO_NOERR); diff --git a/interfaces/kits/js/src/mod_fs/properties/listfile_core.cpp b/interfaces/kits/js/src/mod_fs/properties/listfile_core.cpp new file mode 100644 index 0000000000000000000000000000000000000000..7d334c8a47a11a6165ce4c65a41a78408f976d9f --- /dev/null +++ b/interfaces/kits/js/src/mod_fs/properties/listfile_core.cpp @@ -0,0 +1,310 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "listfile_core.h" + +#include +#include +#include +#include +#include +#include +#include + +#include "file_utils.h" +#include "filemgmt_libhilog.h" + +namespace OHOS::FileManagement::ModuleFileIO { +using namespace std; + +thread_local OptionArgs g_optionArgsCore; + +static bool CheckSuffix(const vector &suffixs) +{ + for (string suffix : suffixs) { + if (suffix.length() <= 1 || suffix.length() > MAX_SUFFIX_LENGTH) { + return false; + } + if (suffix[0] != '.') { + return false; + } + for (size_t i = 1; i < suffix.length(); i++) { + if (!isalnum(suffix[i])) { + return false; + } + } + } + return true; +} + +static bool ValidFileFilterParam(FsFileFilter &fsFilter, FileFilter *filter) +{ + auto suffixs = fsFilter.GetSuffix(); + if (fsFilter.GetSuffix().has_value()) { + vector suffixs = fsFilter.GetSuffix().value(); + if (!CheckSuffix(suffixs) || suffixs.size() == 0) { + HILOGE("Invalid suffix."); + return false; + } + filter->SetSuffix(suffixs); + } + + if (fsFilter.GetDisplayName().has_value()) { + vector displayNames = fsFilter.GetDisplayName().value(); + if (displayNames.size() == 0) { + HILOGE("Invalid displayName."); + return false; + } + filter->SetDisplayName(displayNames); + } + + if (fsFilter.GetFileSizeOver().has_value()) { + int64_t fileSizeOver = fsFilter.GetFileSizeOver().value(); + if (fileSizeOver < 0) { + HILOGE("Failed to get fileSizeOver prop."); + return false; + } + filter->SetFileSizeOver(fileSizeOver); + } + + if (fsFilter.GetLastModifiedAfter().has_value()) { + double lastModifiedAfter = fsFilter.GetLastModifiedAfter().value(); + if (lastModifiedAfter < 0) { + HILOGE("Failed to get lastModifiedAfter prop."); + return false; + } + filter->SetLastModifiedAfter(lastModifiedAfter); + } + + return true; +} + +static bool ValidOptionParam(const string &path, const optional &opt, OptionArgs &optionArgs) +{ + g_optionArgsCore.Clear(); + g_optionArgsCore.path = path; + + if (opt.has_value()) { + auto op = opt.value(); + if (op.listNum < 0) { + HILOGE("Failed to get listNum prop"); + return false; + } + + optionArgs.recursion = op.recursion; + optionArgs.listNum = op.listNum; + + if (op.filter.has_value()) { + bool ret = ValidFileFilterParam(op.filter.value(), &(optionArgs.filter)); + if (!ret) { + HILOGE("Failed to get filter prop."); + return false; + } + } + } + + return true; +} + +static bool FilterSuffix(const vector &suffixs, const struct dirent &filename) +{ + if (filename.d_type == DT_DIR) { + return true; + } + size_t found = string(filename.d_name).rfind('.'); + if (found == std::string::npos) { + return false; + } + string suffixStr = string(filename.d_name).substr(found); + for (const auto &iter : suffixs) { + if (iter == suffixStr) { + return true; + } + } + return false; +} + +static bool FilterDisplayname(const vector &displaynames, const struct dirent &filename) +{ + for (const auto &iter : displaynames) { + int ret = fnmatch(iter.c_str(), filename.d_name, FNM_PATHNAME | FNM_PERIOD); + if (ret == 0) { + return true; + } + } + return false; +} + +static bool FilterFilesizeOver(const int64_t fFileSizeOver, const struct dirent &filename) +{ + if (fFileSizeOver < 0) { + return true; + } + struct stat info; + string stPath = (g_optionArgsCore.path + '/' + string(filename.d_name)); + int32_t res = stat(stPath.c_str(), &info); + if (res != 0) { + HILOGE("Failed to stat file."); + return false; + } + if (info.st_size > fFileSizeOver) { + return true; + } + return false; +} + +static bool FilterLastModifyTime(const double lastModifiedAfter, const struct dirent &filename) +{ + if (lastModifiedAfter < 0) { + return true; + } + struct stat info; + string stPath = g_optionArgsCore.path + '/' + string(filename.d_name); + int32_t res = stat(stPath.c_str(), &info); + if (res != 0) { + HILOGE("Failed to stat file."); + return false; + } + if (static_cast(info.st_mtime) > lastModifiedAfter) { + return true; + } + return false; +} + +static bool FilterResult(const struct dirent &filename) +{ + vector fSuffixs = g_optionArgsCore.filter.GetSuffix(); + if (!FilterSuffix(fSuffixs, filename) && fSuffixs.size() > 0) { + return false; + } + vector fDisplaynames = g_optionArgsCore.filter.GetDisplayName(); + if (!FilterDisplayname(fDisplaynames, filename) && fDisplaynames.size() > 0) { + return false; + } + int64_t fFileSizeOver = g_optionArgsCore.filter.GetFileSizeOver(); + if (!FilterFilesizeOver(fFileSizeOver, filename)) { + return false; + } + double fLastModifiedAfter = g_optionArgsCore.filter.GetLastModifiedAfter(); + if (!FilterLastModifyTime(fLastModifiedAfter, filename)) { + return false; + } + g_optionArgsCore.countNum++; + return true; +} + +static int32_t FilterFunc(const struct dirent *filename) +{ + if (string_view(filename->d_name) == "." || string_view(filename->d_name) == "..") { + return FILTER_DISMATCH; + } + + if (g_optionArgsCore.countNum < g_optionArgsCore.listNum || g_optionArgsCore.listNum == 0) { + if ((filename->d_type == DT_DIR && g_optionArgsCore.recursion) || FilterResult(*filename)) { + return FILTER_MATCH; + } + } + return FILTER_DISMATCH; +} + +static void Deleter(struct NameListArg *arg) +{ + for (int i = 0; i < arg->direntNum; i++) { + free((arg->namelist)[i]); + (arg->namelist)[i] = nullptr; + } + free(arg->namelist); + arg->namelist = nullptr; + delete arg; + arg = nullptr; +} + +static int FilterFileRes(const string &path, vector &dirents) +{ + unique_ptr pNameList = { new (nothrow) struct NameListArg, Deleter }; + if (!pNameList) { + HILOGE("Failed to request heap memory."); + return ENOMEM; + } + int num = scandir(path.c_str(), &(pNameList->namelist), FilterFunc, nullptr); + if (num < 0) { + HILOGE("Failed to scan dir"); + return errno; + } + pNameList->direntNum = num; + for (int i = 0; i < num; i++) { + dirents.emplace_back(pNameList->namelist[i]->d_name); + } + return ERRNO_NOERR; +} + +static int RecursiveFunc(const string &path, vector &dirents) +{ + unique_ptr pNameList = { new (nothrow) struct NameListArg, Deleter }; + if (!pNameList) { + HILOGE("Failed to request heap memory."); + return ENOMEM; + } + int num = scandir(path.c_str(), &(pNameList->namelist), FilterFunc, nullptr); + if (num < 0) { + HILOGE("Failed to scan dir"); + return errno; + } + pNameList->direntNum = num; + for (int i = 0; i < num; i++) { + if ((*(pNameList->namelist[i])).d_type == DT_REG) { + dirents.emplace_back(path + '/' + pNameList->namelist[i]->d_name); + } else if ((*(pNameList->namelist[i])).d_type == DT_DIR) { + string pathTemp = g_optionArgsCore.path; + g_optionArgsCore.path += '/' + string((*(pNameList->namelist[i])).d_name); + int ret = RecursiveFunc(g_optionArgsCore.path, dirents); + if (ret != ERRNO_NOERR) { + return ret; + } + g_optionArgsCore.path = pathTemp; + } + } + return ERRNO_NOERR; +} + +static void DoListFileVector(const string &path, vector &dirents, bool recursion) +{ + if (recursion) { + for (size_t i = 0; i < dirents.size(); i++) { + dirents[i] = dirents[i].substr(path.length()); + } + } +} + +FsResult> ListFileCore::DoListFile(const string &path, const optional &opt) +{ + if (!ValidOptionParam(path, opt, g_optionArgsCore)) { + HILOGE("Invalid options"); + return FsResult>::Error(EINVAL); + } + + vector direntsRes; + int ret = 0; + ret = g_optionArgsCore.recursion ? RecursiveFunc(path, direntsRes) : FilterFileRes(path, direntsRes); + if (ret) { + return FsResult>::Error(ret); + } + DoListFileVector(path, direntsRes, g_optionArgsCore.recursion); + g_optionArgsCore.Clear(); + + return FsResult>::Success(direntsRes); +} + +} // namespace OHOS::FileManagement::ModuleFileIO \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fs/properties/listfile_core.h b/interfaces/kits/js/src/mod_fs/properties/listfile_core.h new file mode 100644 index 0000000000000000000000000000000000000000..f974ad12482837b3e45b3f9dccef704a7afa59a4 --- /dev/null +++ b/interfaces/kits/js/src/mod_fs/properties/listfile_core.h @@ -0,0 +1,71 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef INTERFACES_KITS_JS_SRC_MOD_FS_PROPERTIES_LISTFILE_CORE_H +#define INTERFACES_KITS_JS_SRC_MOD_FS_PROPERTIES_LISTFILE_CORE_H + +#include + +#include "file_filter.h" +#include "filemgmt_libfs.h" +#include "fs_file_filter.h" + +namespace OHOS::FileManagement::ModuleFileIO { +using namespace std; + +struct NameListArg { + struct dirent **namelist = { nullptr }; + int direntNum = 0; +}; + +constexpr int DEFAULT_SIZE = -1; +constexpr int DEFAULT_MODIFY_AFTER = -1; +struct OptionArgs { + FileFilter filter = + FileFilterBuilder().SetFileSizeOver(DEFAULT_SIZE).SetLastModifiedAfter(DEFAULT_MODIFY_AFTER).Build(); + int listNum = 0; + int countNum = 0; + bool recursion = false; + std::string path = ""; + void Clear() + { + filter.FilterClear(); + filter.SetFileSizeOver(DEFAULT_SIZE); + filter.SetLastModifiedAfter(DEFAULT_MODIFY_AFTER); + listNum = 0; + countNum = 0; + recursion = false; + path = ""; + } +}; + +struct FsListFileOptions { + bool recursion = false; + int64_t listNum = 0; + optional filter = nullopt; +}; + +class ListFileCore { +public: + static FsResult> DoListFile( + const std::string &path, const optional &opt = nullopt); +}; + +constexpr int FILTER_MATCH = 1; +constexpr int FILTER_DISMATCH = 0; +const int32_t MAX_SUFFIX_LENGTH = 256; + +} // namespace OHOS::FileManagement::ModuleFileIO +#endif // INTERFACES_KITS_JS_SRC_MOD_FS_PROPERTIES_LISTFILE_CORE_H \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fs/properties/mkdir_core.cpp b/interfaces/kits/js/src/mod_fs/properties/mkdir_core.cpp new file mode 100644 index 0000000000000000000000000000000000000000..cca9bb6e567926180f92ca281e5fc9c86cba1a10 --- /dev/null +++ b/interfaces/kits/js/src/mod_fs/properties/mkdir_core.cpp @@ -0,0 +1,112 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "mkdir_core.h" + +#include +#include +#include +#include +#include +#include + +#include "filemgmt_libhilog.h" + +#if !defined(WIN_PLATFORM) && !defined(IOS_PLATFORM) +#include "rust_file.h" +#endif + +#ifdef FILE_API_TRACE +#include "hitrace_meter.h" +#endif + +namespace OHOS { +namespace FileManagement { +namespace ModuleFileIO { +using namespace std; + +static int UvAccess(const string &path, int mode) +{ + std::unique_ptr accessReq = { new uv_fs_t, FsUtils::FsReqCleanup }; + if (!accessReq) { + HILOGE("Failed to request heap memory."); + return ENOMEM; + } + return uv_fs_access(nullptr, accessReq.get(), path.c_str(), mode, nullptr); +} + +static int MkdirCore(const string &path) +{ + std::unique_ptr mkdirReq = { new uv_fs_t, FsUtils::FsReqCleanup }; + if (!mkdirReq) { + HILOGE("Failed to request heap memory."); + return ENOMEM; + } + return uv_fs_mkdir(nullptr, mkdirReq.get(), path.c_str(), DIR_DEFAULT_PERM, nullptr); +} + +static int32_t MkdirExec(const string &path, bool recursion, bool hasOption) +{ +#if !defined(WIN_PLATFORM) && !defined(IOS_PLATFORM) + if (hasOption) { + int ret = UvAccess(path, 0); + if (ret == ERRNO_NOERR) { + HILOGD("The path already exists"); + return EEXIST; + } + if (ret != -ENOENT) { + HILOGE("Failed to check for illegal path or request for heap memory"); + return ret; + } + if (::Mkdirs(path.c_str(), static_cast(recursion)) < 0) { + HILOGD("Failed to create directories, error: %{public}d", errno); + return errno; + } + ret = UvAccess(path, 0); + if (ret) { + HILOGE("Failed to verify the result of Mkdirs function"); + return ret; + } + return ERRNO_NOERR; + } +#endif + int ret = MkdirCore(path); + if (ret) { + HILOGD("Failed to create directory"); + return ret; + } + return ERRNO_NOERR; +} + +FsResult MkdirCore::DoMkdir(const std::string &path, std::optional recursion) +{ + bool hasOption = false; + bool mkdirRecursion = false; +#if !defined(WIN_PLATFORM) && !defined(IOS_PLATFORM) + hasOption = recursion.has_value(); + if (hasOption) { + mkdirRecursion = recursion.value(); + } +#endif + auto err = MkdirExec(path, mkdirRecursion, hasOption); + if (err) { + return FsResult::Error(err); + } + return FsResult::Success(); +} + +} // namespace ModuleFileIO +} // namespace FileManagement +} // namespace OHOS \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fs/properties/mkdir_core.h b/interfaces/kits/js/src/mod_fs/properties/mkdir_core.h new file mode 100644 index 0000000000000000000000000000000000000000..46bc81a7005e32adade346fba90378a25bc9306d --- /dev/null +++ b/interfaces/kits/js/src/mod_fs/properties/mkdir_core.h @@ -0,0 +1,35 @@ +/* + * Copyright (c) 2022-2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef INTERFACES_KITS_JS_SRC_MOD_FS_PROPERTIES_MKDIR_CORE_H +#define INTERFACES_KITS_JS_SRC_MOD_FS_PROPERTIES_MKDIR_CORE_H + +#include "filemgmt_libfs.h" +#include "fs_utils.h" + +namespace OHOS { +namespace FileManagement { +namespace ModuleFileIO { + +class MkdirCore final { +public: + static FsResult DoMkdir(const std::string& path, std::optional recursion = std::nullopt); +}; +constexpr int DIR_DEFAULT_PERM = 0770; + +} // namespace ModuleFileIO +} // namespace FileManagement +} // namespace OHOS +#endif // INTERFACES_KITS_JS_SRC_MOD_FS_PROPERTIES_MKDIR_CORE_H \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fs/properties/mkdtemp.cpp b/interfaces/kits/js/src/mod_fs/properties/mkdtemp.cpp index 2d8ab18225132cda6d6cb42de3c1f9ab4026e7c4..c304e4a6724b9dc96e85f268b289a4ded0a36d25 100755 --- a/interfaces/kits/js/src/mod_fs/properties/mkdtemp.cpp +++ b/interfaces/kits/js/src/mod_fs/properties/mkdtemp.cpp @@ -69,7 +69,7 @@ static NError MkdTempExec(shared_ptr arg, const string &path) } int ret = uv_fs_mkdtemp(nullptr, mkdtemp_req.get(), path.c_str(), nullptr); if (ret < 0) { - HILOGE("Failed to create a temporary directory with path"); + HILOGE("Failed to create a temporary directory with path ret %{public}d", ret); return NError(ret); } else { *arg = mkdtemp_req->path; diff --git a/interfaces/kits/js/src/mod_fs/properties/move.cpp b/interfaces/kits/js/src/mod_fs/properties/move.cpp index 6898046bc6f4ce1af04fdc63e885dd08183feba1..d6c03bd858734a006b3f6e590b762f2dd83beb44 100644 --- a/interfaces/kits/js/src/mod_fs/properties/move.cpp +++ b/interfaces/kits/js/src/mod_fs/properties/move.cpp @@ -143,7 +143,7 @@ static int RenameFile(const string &src, const string &dest) return CopyAndDeleteFile(src, dest); } if (ret < 0) { - HILOGE("Failed to move file using rename syscall."); + HILOGE("Failed to move file using rename syscall, ret:%{public}d", ret); return ret; } return ERRNO_NOERR; @@ -160,7 +160,7 @@ static int MoveFile(const string &src, const string &dest, int mode) return EEXIST; } if (ret < 0 && (string_view(uv_err_name(ret)) != "ENOENT")) { - HILOGE("Failed to access destPath with MODE_THROW_ERR."); + HILOGE("Failed to access destPath with MODE_THROW_ERR, ret:%{public}d", ret); return ret; } } else { @@ -207,6 +207,7 @@ napi_value Move::Async(napi_env env, napi_callback_info info) auto cbExec = [srcPath = string(src.get()), destPath = string(dest.get()), mode = mode]() -> NError { int ret = MoveFile(srcPath, destPath, mode); if (ret) { + HILOGE("Failed movefile ret %{public}d", ret); return NError(ret); } return NError(ERRNO_NOERR); diff --git a/interfaces/kits/js/src/mod_fs/properties/move_core.cpp b/interfaces/kits/js/src/mod_fs/properties/move_core.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e53ebd5e0e44000f159b2904bc4df7174555236a --- /dev/null +++ b/interfaces/kits/js/src/mod_fs/properties/move_core.cpp @@ -0,0 +1,188 @@ +/* +* Copyright (c) 2025 Huawei Device Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +#include "move_core.h" + +#ifdef __MUSL__ +#include +#else +#include +#endif + +#include +#include + +#include "filemgmt_libhilog.h" +#include "uv.h" + +namespace OHOS { +namespace FileManagement { +namespace ModuleFileIO { +using namespace std; + +#ifdef __MUSL__ +static bool CheckDir(const string &path) +{ + error_code errCode; + if (!filesystem::is_directory(filesystem::status(path, errCode))) { + return false; + } + return true; +} +#else +static bool CheckDir(const string &path) +{ + struct stat fileInformation; + if (stat(path.c_str(), &fileInformation) == 0) { + if (fileInformation.st_mode & S_IFDIR) { + return true; + } + } else { + HILOGE("Failed to stat file"); + } + return false; +} +#endif + +static tuple ValidMoveArg(const string &src, const string &dest, const optional &mode) +{ + if (CheckDir(src)) { + HILOGE("Invalid src"); + return { false, "", "", 0 }; + } + if (CheckDir(dest)) { + HILOGE("Invalid dest"); + return { false, "", "", 0 }; + } + int modeType = 0; + if (mode.has_value()) { + modeType = mode.value(); + if ((modeType != MODE_FORCE_MOVE && modeType != MODE_THROW_ERR)) { + HILOGE("Invalid mode"); + return { false, "", "", 0 }; + } + } + return { true, move(src), move(dest), modeType }; +} + +static int CopyAndDeleteFile(const string &src, const string &dest) +{ + unique_ptr statReq = { + new (nothrow) uv_fs_t, FsUtils::FsReqCleanup }; + if (!statReq) { + HILOGE("Failed to request heap memory."); + return ENOMEM; + } + int ret = uv_fs_stat(nullptr, statReq.get(), src.c_str(), nullptr); + if (ret < 0) { + HILOGE("Failed to stat srcPath"); + return ret; + } +#if !defined(WIN_PLATFORM) && !defined(IOS_PLATFORM) + filesystem::path dstPath(dest); + error_code errCode; + if (filesystem::exists(dstPath, errCode)) { + if (!filesystem::remove(dstPath, errCode)) { + HILOGE("Failed to remove dest file, error code: %{public}d", errCode.value()); + return errCode.value(); + } + } + filesystem::path srcPath(src); + if (!filesystem::copy_file(srcPath, dstPath, filesystem::copy_options::overwrite_existing, errCode)) { + HILOGE("Failed to copy file, error code: %{public}d", errCode.value()); + return errCode.value(); + } +#else + uv_fs_t copyfileReq; + ret = uv_fs_copyfile(nullptr, ©fileReq, src.c_str(), dest.c_str(), MODE_FORCE_MOVE, nullptr); + uv_fs_req_cleanup(©fileReq); + if (ret < 0) { + HILOGE("Failed to move file using copyfile interface."); + return ret; + } +#endif + uv_fs_t unlinkReq; + ret = uv_fs_unlink(nullptr, &unlinkReq, src.c_str(), nullptr); + if (ret < 0) { + HILOGE("Failed to unlink src file"); + int result = uv_fs_unlink(nullptr, &unlinkReq, dest.c_str(), nullptr); + if (result < 0) { + HILOGE("Failed to unlink dest file"); + return result; + } + uv_fs_req_cleanup(&unlinkReq); + return ret; + } + uv_fs_req_cleanup(&unlinkReq); + return ERRNO_NOERR; +} + +static int RenameFile(const string &src, const string &dest) +{ + int ret = 0; + uv_fs_t renameReq; + ret = uv_fs_rename(nullptr, &renameReq, src.c_str(), dest.c_str(), nullptr); + if (ret < 0 && (string_view(uv_err_name(ret)) == "EXDEV")) { + return CopyAndDeleteFile(src, dest); + } + if (ret < 0) { + HILOGE("Failed to move file using rename syscall."); + return ret; + } + return ERRNO_NOERR; +} + +static int MoveFile(const string &src, const string &dest, int mode) +{ + uv_fs_t accessReq; + int ret = uv_fs_access(nullptr, &accessReq, src.c_str(), W_OK, nullptr); + if (ret < 0) { + HILOGE("Failed to move src file due to doesn't exist or hasn't write permission"); + uv_fs_req_cleanup(&accessReq); + return ret; + } + if (mode == MODE_THROW_ERR) { + ret = uv_fs_access(nullptr, &accessReq, dest.c_str(), 0, nullptr); + uv_fs_req_cleanup(&accessReq); + if (ret == 0) { + HILOGE("Failed to move file due to existing destPath with MODE_THROW_ERR."); + return EEXIST; + } + if (ret < 0 && (string_view(uv_err_name(ret)) != "ENOENT")) { + HILOGE("Failed to access destPath with MODE_THROW_ERR."); + return ret; + } + } else { + uv_fs_req_cleanup(&accessReq); + } + return RenameFile(src, dest); +} + +FsResult MoveCore::DoMove(const string &src, const string &dest, const optional &mode) +{ + auto [succ, srcPath, destPath, modeType] = ValidMoveArg(src, dest, mode); + if (!succ) { + return FsResult::Error(EINVAL); + } + int ret = MoveFile(move(srcPath), move(destPath), modeType); + if (ret) { + return FsResult::Error(ret); + } + return FsResult::Success(); +} + +} // namespace ModuleFileIO +} // namespace FileManagement +} // namespace OHOS \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fs/properties/move_core.h b/interfaces/kits/js/src/mod_fs/properties/move_core.h new file mode 100644 index 0000000000000000000000000000000000000000..52ac3b145e4a5eefb55ccd34bb1d06f0c3786d04 --- /dev/null +++ b/interfaces/kits/js/src/mod_fs/properties/move_core.h @@ -0,0 +1,38 @@ +/* +* Copyright (c) 2025 Huawei Device Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +#ifndef INTERFACES_KITS_JS_SRC_MOD_FS_PROPERTIES_MOVE_CORE_H +#define INTERFACES_KITS_JS_SRC_MOD_FS_PROPERTIES_MOVE_CORE_H + +#include +#include "fs_utils.h" +#include "filemgmt_libfs.h" + +namespace OHOS { +namespace FileManagement { +namespace ModuleFileIO { +class MoveCore final { +public: + static FsResult DoMove(const std::string &src, + const std::string &dest, + const std::optional &mode = std::nullopt); +}; +constexpr int MODE_FORCE_MOVE = 0; +constexpr int MODE_THROW_ERR = 1; + +} // namespace ModuleFileIO +} // namespace FileManagement +} // namespace OHOS +#endif \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fs/properties/movedir.cpp b/interfaces/kits/js/src/mod_fs/properties/movedir.cpp index a17abd2d41263f6a7ca31417ea47dc851c48221d..31eee911cb138102da4573430895eb83e6c39769 100644 --- a/interfaces/kits/js/src/mod_fs/properties/movedir.cpp +++ b/interfaces/kits/js/src/mod_fs/properties/movedir.cpp @@ -260,7 +260,7 @@ static int MoveDirFunc(const string &src, const string &dest, const int mode, de if (mode == DIRMODE_DIRECTORY_REPLACE) { int removeRes = RmDirectory(destStr); if (removeRes) { - HILOGE("Failed to remove dest directory in DIRMODE_DIRECTORY_REPLACE"); + HILOGE("Failed to remove dest directory in DIRMODE_DIRECTORY_REPLACE, ret %{public}d", removeRes); return removeRes; } } @@ -277,7 +277,7 @@ static int MoveDirFunc(const string &src, const string &dest, const int mode, de } int removeRes = RmDirectory(src); if (removeRes) { - HILOGE("Failed to remove src directory"); + HILOGE("Failed to remove src directory, ret %{public}d", removeRes); return removeRes; } } diff --git a/interfaces/kits/js/src/mod_fs/properties/open_core.cpp b/interfaces/kits/js/src/mod_fs/properties/open_core.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8ead99468d9e2761f1932c1410595fe6900b82aa --- /dev/null +++ b/interfaces/kits/js/src/mod_fs/properties/open_core.cpp @@ -0,0 +1,206 @@ +/* +* Copyright (c) 2025 Huawei Device Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ +#include "open_core.h" + +#include +#include +#include + +#include "file_entity.h" +#include "file_instantiator.h" +#include "file_utils.h" +#include "filemgmt_libhilog.h" +#include "fs_utils.h" +#if !defined(WIN_PLATFORM) && !defined(IOS_PLATFORM) +#include "ability_manager_client.h" +#include "bundle_info.h" +#include "bundle_mgr_proxy.h" +#include "datashare_helper.h" +#include "file_uri.h" +#include "ipc_skeleton.h" +#include "iservice_registry.h" +#include "remote_uri.h" +#include "status_receiver_host.h" +#include "system_ability_definition.h" +#endif + +#ifdef FILE_API_TRACE +#include "hitrace_meter.h" +#endif + +namespace OHOS { +namespace FileManagement { +namespace ModuleFileIO { +using namespace std; + +#if !defined(WIN_PLATFORM) && !defined(IOS_PLATFORM) +using namespace OHOS::DistributedFS::ModuleRemoteUri; +using namespace OHOS::AppExecFwk; +#endif + +const std::string PROCEDURE_OPEN_NAME = "FileIOOpen"; +const std::string MEDIALIBRARY_DATA_URI = "datashare:///media"; +const std::string FILE_DATA_URI = "file://"; +const std::string PATH_SHARE = "/data/storage/el2/share"; +const std::string MODE_RW = "/rw/"; +const std::string MODE_R = "/r/"; +const std::string MEDIA = "media"; +const std::string DOCS = "docs"; +const std::string DATASHARE = "datashare"; +const std::string SCHEME_BROKER = "content"; +#if !defined(WIN_PLATFORM) && !defined(IOS_PLATFORM) +constexpr uint32_t MAX_WANT_FLAG = 4; +#endif + +static tuple ValidAndConvertFlags(const optional &mode) +{ + uint32_t flags = O_RDONLY; + if (mode.has_value()) { + auto modeValue = mode.value(); + if (modeValue < 0) { + HILOGE("Invalid mode"); + return { false, flags }; + } + flags = static_cast(modeValue); + uint32_t invalidMode = (O_WRONLY | O_RDWR); + if ((flags & invalidMode) == invalidMode) { + HILOGE("Invalid mode"); + return { false, flags }; + } + flags = FsUtils::ConvertFlags(flags); + } + return { true, flags }; +} + +static int OpenFileByPath(const string &path, uint32_t mode) +{ + unique_ptr openReq = { new uv_fs_t, FsUtils::FsReqCleanup }; + if (!openReq) { + HILOGE("Failed to request heap memory."); + return -ENOMEM; + } + int ret = uv_fs_open(nullptr, openReq.get(), path.c_str(), mode, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP, nullptr); + return ret; +} + +#if !defined(WIN_PLATFORM) && !defined(IOS_PLATFORM) + +static int OpenFileByDatashare(const string &path, uint32_t flags) +{ + std::shared_ptr dataShareHelper = nullptr; + sptr remote = new (std::nothrow) IRemoteStub(); + if (!remote) { + HILOGE("Failed to get remote object"); + return -ENOMEM; + } + + dataShareHelper = DataShare::DataShareHelper::Creator(remote->AsObject(), MEDIALIBRARY_DATA_URI); + if (!dataShareHelper) { + HILOGE("Failed to connect to datashare"); + return -E_PERMISSION; + } + Uri uri(path); + int fd = dataShareHelper->OpenFile(uri, FsUtils::GetModeFromFlags(flags)); + return fd; +} + +static tuple OpenByFileDataUri(Uri &uri, const string &uriStr, uint32_t mode) +{ + string bundleName = uri.GetAuthority(); + AppFileService::ModuleFileUri::FileUri fileUri(uriStr); + string realPath = fileUri.GetRealPath(); + if (bundleName == MEDIA) { + int res = OpenFileByDatashare(uri.ToString(), mode); + if (res < 0) { + HILOGE("Failed to open file by Datashare error %{public}d", res); + } + return { res, uri.ToString() }; + } else if (bundleName == DOCS && access(realPath.c_str(), F_OK) != 0) { + int res = OpenFileByDatashare(uri.ToString(), mode); + if (res < 0) { + HILOGE("Failed to open file by Datashare error %{public}d", res); + return { -ENOENT, uri.ToString() }; + } + return { res, uri.ToString() }; + } + int ret = OpenFileByPath(realPath, mode); + if (ret < 0) { + HILOGE("Failed to open file for libuv error %{public}d", ret); + } + return { ret, uriStr }; +} + +static tuple OpenFileByBroker(const Uri &uri, uint32_t mode) +{ + uint32_t flag = (mode % MAX_WANT_FLAG) > 0 ? AAFwk::Want::FLAG_AUTH_WRITE_URI_PERMISSION + : AAFwk::Want::FLAG_AUTH_READ_URI_PERMISSION; + int ret = AAFwk::AbilityManagerClient::GetInstance()->OpenFile(uri, flag); + if (ret < 0) { + HILOGE("Failed to open file by Broker error %{public}d", ret); + } + return { ret, uri.ToString() }; +} + +static tuple OpenFileByUri(const string &path, uint32_t mode) +{ + Uri uri(path); + string uriType = uri.GetScheme(); + if (uriType == SCHEME_FILE) { + return OpenByFileDataUri(uri, path, mode); + } + if (uriType == SCHEME_BROKER) { + return OpenFileByBroker(uri, mode); + } + int fd = -1; + if (uriType == DATASHARE && RemoteUri::IsRemoteUri(path, fd, mode)) { + if (fd >= 0) { + return { fd, path }; + } + HILOGE("Failed to open file by RemoteUri"); + } + HILOGE("Failed to open file by invalid uri"); + return { -EINVAL, path }; +} +#endif + +FsResult OpenCore::DoOpen(const string &path, const optional &mode) +{ +#ifdef FILE_API_TRACE + HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); +#endif + auto [succMode, modeValue] = ValidAndConvertFlags(mode); + if (!succMode) { + return FsResult::Error(EINVAL); + } +#if !defined(WIN_PLATFORM) && !defined(IOS_PLATFORM) + if (path.find("://") != string::npos) { + auto [res, uriStr] = OpenFileByUri(path, modeValue); + if (res < 0) { + return FsResult::Error(res); + } + return FileInstantiator::InstantiateFile(res, uriStr, true); + } +#endif + int ret = OpenFileByPath(path, modeValue); + if (ret < 0) { + HILOGD("Failed to open file for libuv error %{public}d", ret); + return FsResult::Error(ret); + } + return FileInstantiator::InstantiateFile(ret, path, false); +} + +} // namespace ModuleFileIO +} // namespace FileManagement +} // namespace OHOS \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fs/properties/open_core.h b/interfaces/kits/js/src/mod_fs/properties/open_core.h new file mode 100644 index 0000000000000000000000000000000000000000..963b052d4b123ee7b85b41195d9114f771ef9722 --- /dev/null +++ b/interfaces/kits/js/src/mod_fs/properties/open_core.h @@ -0,0 +1,29 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef INTERFACES_KITS_JS_SRC_MOD_FS_PROPERTIES_OPEN_CORE_H +#define INTERFACES_KITS_JS_SRC_MOD_FS_PROPERTIES_OPEN_CORE_H + +#include "filemgmt_libfs.h" +#include "fs_file.h" + +namespace OHOS::FileManagement::ModuleFileIO { +class OpenCore final { +public: + static FsResult DoOpen(const std::string &path, const std::optional &mode = std::nullopt); +}; + +} // namespace OHOS::FileManagement::ModuleFileIO +#endif // INTERFACES_KITS_JS_SRC_MOD_FS_PROPERTIES_OPEN_CORE_H \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fs/properties/prop_n_exporter.cpp b/interfaces/kits/js/src/mod_fs/properties/prop_n_exporter.cpp index 1191c331106aa3a427ea92087dda8bc36c68d909..b1ff25baf86f626a5acf04334a9662cd96df89d9 100644 --- a/interfaces/kits/js/src/mod_fs/properties/prop_n_exporter.cpp +++ b/interfaces/kits/js/src/mod_fs/properties/prop_n_exporter.cpp @@ -263,7 +263,7 @@ napi_value PropNExporter::AccessSync(napi_env env, napi_callback_info info) bool isAccess = false; int ret = AccessCore(args.path, args.mode, args.flag); if (ret < 0 && (string_view(uv_err_name(ret)) != "ENOENT")) { - HILOGE("Failed to access file by path"); + HILOGE("Failed to access file by path, ret:%{public}d", ret); NError(ret).ThrowErr(env); return nullptr; } @@ -296,6 +296,9 @@ napi_value PropNExporter::Access(napi_env env, napi_callback_info info) } auto cbExec = [path = args.path, result, mode = args.mode, flag = args.flag]() -> NError { int ret = AccessCore(path, mode, flag); + if (ret < 0) { + HILOGE("Accesscore finish ret %{public}d", ret); + } if (ret == 0) { result->isAccess = true; } @@ -343,7 +346,7 @@ napi_value PropNExporter::Unlink(napi_env env, napi_callback_info info) } int ret = uv_fs_unlink(nullptr, unlink_req.get(), path.c_str(), nullptr); if (ret < 0) { - HILOGD("Failed to unlink with path"); + HILOGD("Failed to unlink with path ret %{public}d", ret); return NError(ret); } return NError(ERRNO_NOERR); @@ -390,7 +393,7 @@ napi_value PropNExporter::UnlinkSync(napi_env env, napi_callback_info info) } int ret = uv_fs_unlink(nullptr, unlink_req.get(), path.get(), nullptr); if (ret < 0) { - HILOGD("Failed to unlink with path"); + HILOGD("Failed to unlink with path ret %{public}d", ret); NError(ret).ThrowErr(env); return nullptr; } @@ -419,7 +422,7 @@ static NError MkdirExec(const string &path, bool recursion, bool hasOption) return NError(EEXIST); } if (ret != -ENOENT) { - HILOGE("Failed to check for illegal path or request for heap memory"); + HILOGE("Failed to check for illegal path or request for heap memory, ret: %{public}d", ret); return NError(ret); } if (::Mkdirs(path.c_str(), static_cast(recursion)) < 0) { @@ -428,7 +431,7 @@ static NError MkdirExec(const string &path, bool recursion, bool hasOption) } ret = AccessCore(path, 0); if (ret) { - HILOGE("Failed to verify the result of Mkdirs function"); + HILOGE("Failed to verify the result of Mkdirs function, ret: %{public}d", ret); return NError(ret); } return NError(ERRNO_NOERR); diff --git a/interfaces/kits/js/src/mod_fs/properties/read_core.cpp b/interfaces/kits/js/src/mod_fs/properties/read_core.cpp new file mode 100644 index 0000000000000000000000000000000000000000..2099ebce63eb8ca42436d1a78e60305fc5247ad7 --- /dev/null +++ b/interfaces/kits/js/src/mod_fs/properties/read_core.cpp @@ -0,0 +1,92 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "read_core.h" + +#include +#include +#include + +#include + +#include "file_utils.h" +#include "filemgmt_libfs.h" +#include "filemgmt_libhilog.h" + +namespace OHOS::FileManagement::ModuleFileIO { +using namespace std; + +static tuple ValidReadArg(ArrayBuffer &arrayBuffer, const optional &options) +{ + size_t retLen = 0; + int64_t offset = -1; + bool succ = false; + void *buf = arrayBuffer.buf; + size_t bufLen = arrayBuffer.length; + + if (bufLen > UINT_MAX) { + HILOGE("Invalid arraybuffer"); + return { false, nullptr, retLen, offset }; + } + optional lengthOp = nullopt; + optional offsetOp = nullopt; + if (options.has_value()) { + ReadOptions op = options.value(); + lengthOp = op.length; + offsetOp = op.offset; + } + tie(succ, retLen) = FsUtils::GetActualLen(bufLen, 0, lengthOp); + if (!succ) { + HILOGE("Failed to get actual length"); + return { false, nullptr, retLen, offset }; + } + if (offsetOp.has_value()) { + offset = offsetOp.value(); + if (offset < 0) { + HILOGE("option.offset shall be positive number"); + return { false, nullptr, retLen, offset }; + } + } + return { true, buf, retLen, offset }; +} + +FsResult ReadCore::DoRead(const int32_t &fd, ArrayBuffer &arrayBuffer, const optional &options) +{ + if (fd < 0) { + HILOGE("Invalid fd"); + return FsResult::Error(EINVAL); + } + + auto [succ, buf, len, offset] = ValidReadArg(arrayBuffer, options); + if (!succ) { + return FsResult::Error(EINVAL); + } + + uv_buf_t buffer = uv_buf_init(static_cast(buf), static_cast(len)); + unique_ptr readReq = { new uv_fs_t, FsUtils::FsReqCleanup }; + if (!readReq) { + HILOGE("Failed to request heap memory."); + return FsResult::Error(ENOMEM); + } + int ret = uv_fs_read(nullptr, readReq.get(), fd, &buffer, 1, offset, nullptr); + if (ret < 0) { + HILOGE("Failed to read file for %{public}d", ret); + return FsResult::Error(ret); + } + + return FsResult::Success(static_cast(ret)); +} + +} // namespace OHOS::FileManagement::ModuleFileIO \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fs/properties/read_core.h b/interfaces/kits/js/src/mod_fs/properties/read_core.h new file mode 100644 index 0000000000000000000000000000000000000000..5c99656734e0eb1da8a184e8ee43df0eba6fb987 --- /dev/null +++ b/interfaces/kits/js/src/mod_fs/properties/read_core.h @@ -0,0 +1,38 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef INTERFACES_KITS_JS_SRC_MOD_FS_PROPERTIES_READ_CORE_H +#define INTERFACES_KITS_JS_SRC_MOD_FS_PROPERTIES_READ_CORE_H + +#include +#include "filemgmt_libfs.h" +#include "fs_utils.h" + +namespace OHOS::FileManagement::ModuleFileIO { +using namespace std; + +struct ReadOptions final { + optional offset = nullopt; + optional length = nullopt; +}; + +class ReadCore final { +public: + static FsResult DoRead( + const int32_t &fd, ArrayBuffer &arrayBuffer, const optional &options = nullopt); +}; + +} // namespace OHOS::FileManagement::ModuleFileIO +#endif // INTERFACES_KITS_JS_SRC_MOD_FS_PROPERTIES_READ_CORE_H \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fs/properties/read_lines.cpp b/interfaces/kits/js/src/mod_fs/properties/read_lines.cpp index dc94ed0fe8f07a9ed810998fe1e64f37a739aff9..2a314241030e0f64758468d461560585c4ca668e 100644 --- a/interfaces/kits/js/src/mod_fs/properties/read_lines.cpp +++ b/interfaces/kits/js/src/mod_fs/properties/read_lines.cpp @@ -112,7 +112,7 @@ static NError AsyncExec(ReaderIteratorArg &readerIterator, const string &pathStr } int ret = GetFileSize(pathStr, readerIterator.offset); if (ret < 0) { - HILOGE("Failed to get size of the file"); + HILOGE("Failed to get size of the file ret %{public}d", ret); return NError(ret); } diff --git a/interfaces/kits/js/src/mod_fs/properties/read_text_core.cpp b/interfaces/kits/js/src/mod_fs/properties/read_text_core.cpp new file mode 100644 index 0000000000000000000000000000000000000000..90b1b71095eca8e106dad4fa14cd74ac48a44d30 --- /dev/null +++ b/interfaces/kits/js/src/mod_fs/properties/read_text_core.cpp @@ -0,0 +1,138 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include "read_text_core.h" + +#include +#include +#include +#include +#include + +#include "file_utils.h" +#include "filemgmt_libhilog.h" + +namespace OHOS { +namespace FileManagement { +namespace ModuleFileIO { +using namespace std; + +static tuple> ValidReadTextArg( + const std::optional &options) +{ + int64_t offset = -1; + int64_t len = 0; + bool hasLen = false; + unique_ptr encoding { new char[]{ "utf-8" } }; + + if (!options.has_value()) { + return { true, offset, hasLen, len, move(encoding) }; + } + + ReadTextOptions op = options.value(); + if (op.offset.has_value()) { + offset = op.offset.value(); + if (offset < 0) { + HILOGE("Illegal option.offset parameter"); + return { false, offset, hasLen, len, nullptr }; + } + } + + if (op.length.has_value()) { + len = op.length.value(); + if (len < 0 || len > UINT_MAX) { + HILOGE("Illegal option.length parameter"); + return { false, offset, hasLen, len, nullptr }; + } + hasLen = true; + } + + if (op.encoding.has_value()) { + auto encoding = op.encoding.value(); + if (encoding != "utf-8") { + HILOGE("Illegal option.encoding parameter"); + return { false, offset, hasLen, len, nullptr }; + } + } + + return { true, offset, hasLen, len, move(encoding) }; +} + +static int OpenFile(const std::string& path) +{ + std::unique_ptr openReq = { + new uv_fs_t, FsUtils::FsReqCleanup + }; + if (openReq == nullptr) { + HILOGE("Failed to request heap memory."); + return -ENOMEM; + } + + return uv_fs_open(nullptr, openReq.get(), path.c_str(), O_RDONLY, + S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP, nullptr); +} + +static int ReadFromFile(int fd, int64_t offset, string& buffer) +{ + uv_buf_t readbuf = uv_buf_init(const_cast(buffer.c_str()), static_cast(buffer.size())); + std::unique_ptr readReq = { + new uv_fs_t, FsUtils::FsReqCleanup }; + if (readReq == nullptr) { + HILOGE("Failed to request heap memory."); + return -ENOMEM; + } + return uv_fs_read(nullptr, readReq.get(), fd, &readbuf, 1, offset, nullptr); +} + +FsResult> ReadTextCore::DoReadText(const std::string &path, + const std::optional &options) +{ + auto [resGetReadTextArg, offset, hasLen, len, encoding] = ValidReadTextArg(options); + if (!resGetReadTextArg) { + return FsResult>::Error(EINVAL); + } + + OHOS::DistributedFS::FDGuard sfd; + int fd = OpenFile(path); + if (fd < 0) { + HILOGD("Failed to open file by ret: %{public}d", fd); + return FsResult>::Error(fd); + } + sfd.SetFD(fd); + + struct stat statbf; + if ((!sfd) || (fstat(sfd.GetFD(), &statbf) < 0)) { + HILOGE("Failed to get stat of file by fd: %{public}d", sfd.GetFD()); + return FsResult>::Error(errno); + } + + if (offset > statbf.st_size) { + HILOGE("Invalid offset: %{public}" PRIu64, offset); + return FsResult>::Error(EINVAL); + } + + len = (!hasLen || len > statbf.st_size) ? statbf.st_size : len; + string buffer(len, '\0'); + int readRet = ReadFromFile(sfd.GetFD(), offset, buffer); + if (readRet < 0) { + HILOGE("Failed to read file by fd: %{public}d", fd); + return FsResult>::Error(readRet); + } + + return FsResult>::Success(make_tuple(move(buffer), readRet)); +} + +} // namespace ModuleFileIO +} // namespace FileManagement +} // namespace OHOS \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fs/properties/read_text_core.h b/interfaces/kits/js/src/mod_fs/properties/read_text_core.h new file mode 100644 index 0000000000000000000000000000000000000000..19ce93ffc81d0d7d1f7366ab60da8d5d12c54a19 --- /dev/null +++ b/interfaces/kits/js/src/mod_fs/properties/read_text_core.h @@ -0,0 +1,42 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef INTERFACES_KITS_JS_SRC_MOD_FS_PROPERTIES_READ_TEXT_CORE_H +#define INTERFACES_KITS_JS_SRC_MOD_FS_PROPERTIES_READ_TEXT_CORE_H + +#include "filemgmt_libfs.h" +#include "fs_utils.h" + +namespace OHOS { +namespace FileManagement { +namespace ModuleFileIO { +using namespace std; + +struct ReadTextOptions final { + optional offset = nullopt; + optional length = nullopt; + optional encoding = nullopt; +}; + +class ReadTextCore final { +public: + static FsResult> DoReadText(const string &filePath, + const optional &options = nullopt); +}; + +} // namespace ModuleFileIO +} // namespace FileManagement +} // namespace OHOS +#endif // INTERFACES_KITS_JS_SRC_MOD_FS_PROPERTIES_READ_TEXT_CORE_H \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fs/properties/rename.cpp b/interfaces/kits/js/src/mod_fs/properties/rename.cpp index 30aef30f9ed90df1d33370fbcfab2ab7f7b286ef..c71258c943288635d398b23c42c4ac1bf57af68f 100755 --- a/interfaces/kits/js/src/mod_fs/properties/rename.cpp +++ b/interfaces/kits/js/src/mod_fs/properties/rename.cpp @@ -60,7 +60,7 @@ napi_value Rename::Sync(napi_env env, napi_callback_info info) } int ret = uv_fs_rename(nullptr, rename_req.get(), src.get(), dest.get(), nullptr); if (ret < 0) { - HILOGE("Failed to rename file with path"); + HILOGE("Failed to rename file with path ret %{public}d", ret); NError(ret).ThrowErr(env); return nullptr; } @@ -100,7 +100,7 @@ napi_value Rename::Async(napi_env env, napi_callback_info info) } int ret = uv_fs_rename(nullptr, rename_req.get(), opath.c_str(), npath.c_str(), nullptr); if (ret < 0) { - HILOGE("Failed to rename file with path"); + HILOGE("Failed to rename file with path ret %{public}d", ret); return NError(ret); } return NError(ERRNO_NOERR); diff --git a/interfaces/kits/js/src/mod_fs/properties/rmdir_core.cpp b/interfaces/kits/js/src/mod_fs/properties/rmdir_core.cpp new file mode 100644 index 0000000000000000000000000000000000000000..fd37c3be883a23807d096f8d438d30c08f80fd46 --- /dev/null +++ b/interfaces/kits/js/src/mod_fs/properties/rmdir_core.cpp @@ -0,0 +1,122 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "rmdir_core.h" + +#include +#include +#include +#include +#include + +#include +#include + +#include "filemgmt_libhilog.h" + +namespace OHOS { +namespace FileManagement { +namespace ModuleFileIO { +using namespace std; + +#ifdef __MUSL__ +static int32_t RmDirent(const string &fpath) +{ + std::filesystem::path strToPath(fpath); + std::error_code errCode; + std::uintmax_t num = std::filesystem::remove_all(strToPath, errCode); + if (errCode.value() != ERRNO_NOERR) { + HILOGD("Failed to remove directory, error code: %{public}d", errCode.value()); + return errCode.value(); + } + if (!num || std::filesystem::exists(strToPath, errCode)) { + HILOGE("Failed to remove directory, dirPath does not exist"); + return ENOENT; + } + if (errCode.value() != ERRNO_NOERR) { + HILOGE("fs exists fail, error code: %{public}d", errCode.value()); + return errCode.value(); + } + return ERRNO_NOERR; +} + +#else +static int32_t RmDirent(const string &fpath) +{ + std::unique_ptr scandirReq = { + new (std::nothrow) uv_fs_t, FsUtils::FsReqCleanup }; + if (!scandirReq) { + HILOGE("Failed to request heap memory."); + return ENOMEM; + } + int ret = 0; + ret = uv_fs_scandir(nullptr, scandirReq.get(), fpath.c_str(), 0, nullptr); + if (ret < 0) { + HILOGE("Failed to scandir, ret: %{public}d", ret); + return ret; + } + uv_dirent_t dent; + while (uv_fs_scandir_next(scandirReq.get(), &dent) != UV_EOF) { + string filePath = fpath + "/" + string(dent.name); + if (dent.type == UV_DIRENT_FILE) { + std::unique_ptr unlinkReq = { + new (std::nothrow) uv_fs_t, FsUtils::FsReqCleanup }; + if (!unlinkReq) { + HILOGE("Failed to request heap memory."); + return ENOMEM; + } + ret = uv_fs_unlink(nullptr, unlinkReq.get(), filePath.c_str(), nullptr); + if (ret < 0) { + HILOGE("Failed to unlink file, ret: %{public}d", ret); + return ret; + } + } else if (dent.type == UV_DIRENT_DIR) { + auto rmDirentRes = RmDirent(filePath); + if (rmDirentRes) { + return rmDirentRes; + } + } + } + std::unique_ptr rmdirReq = { + new (std::nothrow) uv_fs_t, FsUtils::FsReqCleanup}; + if (!rmdirReq) { + HILOGE("Failed to request heap memory."); + return ENOMEM; + } + ret = uv_fs_rmdir(nullptr, rmdirReq.get(), fpath.c_str(), nullptr); + if (ret < 0) { + HILOGE("Failed to rmdir empty dir, ret: %{public}d", ret); + return ret; + } + return ERRNO_NOERR; +} +#endif + +FsResult RmdirentCore::DoRmdirent(const string &fpath) +{ + if (fpath.empty()) { + HILOGE("Invalid path"); + return FsResult::Error(EINVAL); + } + + auto err = RmDirent(fpath); + if (err) { + return FsResult::Error(err); + } + return FsResult::Success(); +} +} // namespace ModuleFileIO +} // namespace FileManagement +} // namespace OHOS \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fs/properties/rmdir_core.h b/interfaces/kits/js/src/mod_fs/properties/rmdir_core.h new file mode 100644 index 0000000000000000000000000000000000000000..036f8e5461823a41dd8fa3c4173634e36f7c49df --- /dev/null +++ b/interfaces/kits/js/src/mod_fs/properties/rmdir_core.h @@ -0,0 +1,33 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef INTERFACES_KITS_JS_SRC_MOD_FS_PROPERTIES_RMDIR_CORE_H +#define INTERFACES_KITS_JS_SRC_MOD_FS_PROPERTIES_RMDIR_CORE_H + +#include "filemgmt_libfs.h" +#include "fs_utils.h" + +namespace OHOS { +namespace FileManagement { +namespace ModuleFileIO { +class RmdirentCore final { +public: + static FsResult DoRmdirent(const std::string &fpath); +}; + +} // namespace ModuleFileIO +} // namespace FileManagement +} // namespace OHOS +#endif // INTERFACES_KITS_JS_SRC_MOD_FS_PROPERTIES_RMDIR_CORE_H \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fs/properties/stat_core.cpp b/interfaces/kits/js/src/mod_fs/properties/stat_core.cpp new file mode 100644 index 0000000000000000000000000000000000000000..17269b133fb7f66373d5a25435992dbed45fbb31 --- /dev/null +++ b/interfaces/kits/js/src/mod_fs/properties/stat_core.cpp @@ -0,0 +1,124 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "stat_core.h" + +#include +#include +#include + +#include "file_utils.h" +#include "filemgmt_libhilog.h" +#include "fs_stat_entity.h" +#include "stat_instantiator.h" + +namespace OHOS::FileManagement::ModuleFileIO { +using namespace std; + +static bool IsPath(const FileInfo &fileInfo) +{ + auto path = fileInfo.path.get(); + if (path == nullptr || strlen(path) == 0) { + return false; + } + return true; +} + +static tuple IsFd(const FileInfo &fileInfo) +{ + auto fdg = fileInfo.fdg.get(); + if (fdg == nullptr) { + return make_tuple(false, 0); + } + return make_tuple(true, fdg->GetFD()); +} + +static tuple ValidFileInfo(const FileInfo &fileInfo) +{ + auto isPath = IsPath(fileInfo); + if (isPath) { + auto &path = const_cast &>(fileInfo.path); + return { true, FileInfo { true, move(path), {} } }; + } + auto [isFd, fd] = IsFd(fileInfo); + if (isFd) { + if (fd < 0) { + HILOGE("Invalid fd"); + return { false, FileInfo { false, {}, {} } }; + } + auto fdg = CreateUniquePtr(fd, false); + if (fdg == nullptr) { + HILOGE("Failed to request heap memory."); + return { false, FileInfo { false, {}, {} } }; + } + return { true, FileInfo { false, {}, move(fdg) } }; + } + HILOGE("Invalid parameter"); + return { false, FileInfo { false, {}, {} } }; +}; + +static int32_t CheckFsStat(const FileInfo &fileInfo, uv_fs_t *req) +{ + if (fileInfo.isPath) { + int ret = uv_fs_stat(nullptr, req, fileInfo.path.get(), nullptr); + if (ret < 0) { + HILOGD("Failed to stat file with path, ret is %{public}d", ret); + return ret; + } + } else { + int ret = uv_fs_fstat(nullptr, req, fileInfo.fdg->GetFD(), nullptr); + if (ret < 0) { + HILOGE("Failed to stat file with fd, ret is %{public}d", ret); + return ret; + } + } + return ERRNO_NOERR; +} + +FsResult StatCore::DoStat(const FileInfo &fileinfo) +{ + auto [succ, info] = ValidFileInfo(fileinfo); + if (!succ) { + return FsResult::Error(EINVAL); + } + + std::unique_ptr statReq = { new (std::nothrow) uv_fs_t, + FsUtils::FsReqCleanup }; + if (!statReq) { + HILOGE("Failed to request heap memory."); + return FsResult::Error(ENOMEM); + } + auto err = CheckFsStat(info, statReq.get()); + if (err) { + return FsResult::Error(err); + } + +#if !defined(WIN_PLATFORM) && !defined(IOS_PLATFORM) + auto arg = CreateSharedPtr(move(info)); + if (arg == nullptr) { + HILOGE("Failed to request heap memory."); + return FsResult::Error(ENOMEM); + } + auto stat = StatInstantiator::InstantiateStat(statReq->statbuf, arg); +#else + auto stat = StatInstantiator::InstantiateStat(statReq->statbuf); +#endif + if (stat == nullptr) { + return FsResult::Error(ENOMEM); + } + return FsResult::Success(stat); +} + +} // namespace OHOS::FileManagement::ModuleFileIO \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fs/properties/stat_core.h b/interfaces/kits/js/src/mod_fs/properties/stat_core.h new file mode 100644 index 0000000000000000000000000000000000000000..28d7a5f55c45655854a6e1d892a42e5e8ba5159f --- /dev/null +++ b/interfaces/kits/js/src/mod_fs/properties/stat_core.h @@ -0,0 +1,30 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef INTERFACES_KITS_JS_SRC_MOD_FS_PROPERTIES_STAT_CORE_H +#define INTERFACES_KITS_JS_SRC_MOD_FS_PROPERTIES_STAT_CORE_H + +#include "filemgmt_libfs.h" +#include "fs_stat.h" +#include "fs_utils.h" + +namespace OHOS::FileManagement::ModuleFileIO { +class StatCore final { +public: + static FsResult DoStat(const FileInfo &fileinfo); +}; + +} // namespace OHOS::FileManagement::ModuleFileIO +#endif // INTERFACES_KITS_JS_SRC_MOD_FS_PROPERTIES_STAT_CORE_H \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fs/properties/symlink.cpp b/interfaces/kits/js/src/mod_fs/properties/symlink.cpp index 3ada5d1496251bb11a4ef34340ca6a5c86f5cd96..a83e8e18796a6670e5c5209a06ad43b0d48a6bd0 100755 --- a/interfaces/kits/js/src/mod_fs/properties/symlink.cpp +++ b/interfaces/kits/js/src/mod_fs/properties/symlink.cpp @@ -69,7 +69,7 @@ napi_value Symlink::Sync(napi_env env, napi_callback_info info) } int ret = uv_fs_symlink(nullptr, symlink_req.get(), oldPath.c_str(), newPath.c_str(), 0, nullptr); if (ret < 0) { - HILOGE("Failed to create a link for old path"); + HILOGE("Failed to create a link for old path ret %{public}d", ret); NError(ret).ThrowErr(env); return nullptr; } @@ -102,7 +102,7 @@ napi_value Symlink::Async(napi_env env, napi_callback_info info) } int ret = uv_fs_symlink(nullptr, symlink_req.get(), oldPath.c_str(), newPath.c_str(), 0, nullptr); if (ret < 0) { - HILOGE("Failed to create a link for old path"); + HILOGE("Failed to create a link for old path ret %{public}d", ret); return NError(ret); } return NError(ERRNO_NOERR); diff --git a/interfaces/kits/js/src/mod_fs/properties/truncate.cpp b/interfaces/kits/js/src/mod_fs/properties/truncate.cpp index 3e2837433ed8b101779f2ffd92c4028368b85a64..4691f446be0131cb52e5ac1670ec6c86cd16da02 100644 --- a/interfaces/kits/js/src/mod_fs/properties/truncate.cpp +++ b/interfaces/kits/js/src/mod_fs/properties/truncate.cpp @@ -60,6 +60,7 @@ static NError TruncateCore(napi_env env, FileInfo &fileInfo, int64_t truncateLen int ret = uv_fs_open(nullptr, open_req.get(), fileInfo.path.get(), O_RDWR, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP, nullptr); if (ret < 0) { + HILOGE("Failed to open by libuv ret %{public}d", ret); return NError(ret); } std::unique_ptr ftruncate_req = { @@ -70,7 +71,7 @@ static NError TruncateCore(napi_env env, FileInfo &fileInfo, int64_t truncateLen } ret = uv_fs_ftruncate(nullptr, ftruncate_req.get(), ret, truncateLen, nullptr); if (ret < 0) { - HILOGE("Failed to truncate file by path"); + HILOGE("Failed to truncate file by path ret %{public}d", ret); return NError(ret); } } else { diff --git a/interfaces/kits/js/src/mod_fs/properties/truncate_core.cpp b/interfaces/kits/js/src/mod_fs/properties/truncate_core.cpp new file mode 100644 index 0000000000000000000000000000000000000000..66b68f185be7c5dfa419e1028db09190e175003c --- /dev/null +++ b/interfaces/kits/js/src/mod_fs/properties/truncate_core.cpp @@ -0,0 +1,104 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "truncate_core.h" + +#include +#include +#include + +#include "file_utils.h" +#include "filemgmt_libhilog.h" + +namespace OHOS::FileManagement::ModuleFileIO { +using namespace std; + +static bool ValidFileInfo(FileInfo &fileInfo) +{ + if (!fileInfo.isPath) { + auto fd = fileInfo.fdg->GetFD(); + if (fd < 0) { + HILOGE("Invalid fd"); + return false; + } + } + return true; +} + +static int Truncate(FileInfo &fileInfo, int64_t truncateLen) +{ + if (fileInfo.isPath) { + std::unique_ptr openReq = { new uv_fs_t, FsUtils::FsReqCleanup }; + if (!openReq) { + HILOGE("Failed to request heap memory."); + return ENOMEM; + } + int ret = uv_fs_open( + nullptr, openReq.get(), fileInfo.path.get(), O_RDWR, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP, nullptr); + if (ret < 0) { + return ret; + } + std::unique_ptr ftruncateReq = { new uv_fs_t, + FsUtils::FsReqCleanup }; + if (!ftruncateReq) { + HILOGE("Failed to request heap memory."); + return ENOMEM; + } + ret = uv_fs_ftruncate(nullptr, ftruncateReq.get(), ret, truncateLen, nullptr); + if (ret < 0) { + HILOGE("Failed to truncate file by path"); + return ret; + } + } else { + std::unique_ptr ftruncateReq = { new uv_fs_t, + FsUtils::FsReqCleanup }; + if (!ftruncateReq) { + HILOGE("Failed to request heap memory."); + return ENOMEM; + } + int ret = uv_fs_ftruncate(nullptr, ftruncateReq.get(), fileInfo.fdg->GetFD(), truncateLen, nullptr); + if (ret < 0) { + HILOGE("Failed to truncate file by fd for libuv error %{public}d", ret); + return ret; + } + } + return ERRNO_NOERR; +} + +FsResult TruncateCore::DoTruncate(FileInfo &fileInfo, const std::optional &len) + +{ + auto succ = ValidFileInfo(fileInfo); + if (!succ) { + return FsResult::Error(EINVAL); + } + + int64_t truncateLen = 0; + if (len.has_value()) { + truncateLen = len.value(); + if (truncateLen < 0) { + HILOGE("Invalid truncate length"); + return FsResult::Error(EINVAL); + } + } + + auto err = Truncate(fileInfo, truncateLen); + if (err) { + return FsResult::Error(err); + } + + return FsResult::Success(); +} +} // namespace OHOS::FileManagement::ModuleFileIO \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fs/properties/truncate_core.h b/interfaces/kits/js/src/mod_fs/properties/truncate_core.h new file mode 100644 index 0000000000000000000000000000000000000000..5803b46eb924beebcc3c412b0e7a7ae8b9b99c50 --- /dev/null +++ b/interfaces/kits/js/src/mod_fs/properties/truncate_core.h @@ -0,0 +1,30 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef INTERFACES_KITS_JS_SRC_MOD_FS_PROPERTIES_TRUNCATE_CORE_H +#define INTERFACES_KITS_JS_SRC_MOD_FS_PROPERTIES_TRUNCATE_CORE_H + +#include "filemgmt_libfs.h" +#include "fs_utils.h" + +namespace OHOS::FileManagement::ModuleFileIO { + +class TruncateCore final { +public: + static FsResult DoTruncate(FileInfo &fileInfo, const std::optional &len = std::nullopt); +}; + +} // namespace OHOS::FileManagement::ModuleFileIO +#endif // INTERFACES_KITS_JS_SRC_MOD_FS_PROPERTIES_TRUNCATE_CORE_H \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fs/properties/unlink_core.cpp b/interfaces/kits/js/src/mod_fs/properties/unlink_core.cpp new file mode 100644 index 0000000000000000000000000000000000000000..339b56db0664a30f426edd4bedc2e173952569ab --- /dev/null +++ b/interfaces/kits/js/src/mod_fs/properties/unlink_core.cpp @@ -0,0 +1,48 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "unlink_core.h" + +#ifdef FILE_API_TRACE +#include "hitrace_meter.h" +#endif + +#include "filemgmt_libhilog.h" + +namespace OHOS { +namespace FileManagement { +namespace ModuleFileIO { +using namespace std; + +FsResult UnlinkCore::DoUnlink(const std::string &src) +{ + std::unique_ptr unlinkReq = { + new uv_fs_t, FsUtils::FsReqCleanup }; + if (!unlinkReq) { + HILOGE("Failed to request heap memory."); + return FsResult::Error(ENOMEM); + } + int ret = uv_fs_unlink(nullptr, unlinkReq.get(), src.c_str(), nullptr); + if (ret < 0) { + HILOGD("Failed to unlink with path"); + return FsResult::Error(ret); + } + + return FsResult::Success(); +} + +} // namespace ModuleFileIO +} // namespace FileManagement +} // namespace OHOS \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fs/properties/unlink_core.h b/interfaces/kits/js/src/mod_fs/properties/unlink_core.h new file mode 100644 index 0000000000000000000000000000000000000000..5989bbda29217d938c1f539bedc29197198be31c --- /dev/null +++ b/interfaces/kits/js/src/mod_fs/properties/unlink_core.h @@ -0,0 +1,34 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef INTERFACES_KITS_JS_SRC_MOD_FS_PROPERTIES_UNLINK_CORE_H +#define INTERFACES_KITS_JS_SRC_MOD_FS_PROPERTIES_UNLINK_CORE_H + +#include "filemgmt_libfs.h" +#include "fs_utils.h" + +namespace OHOS { +namespace FileManagement { +namespace ModuleFileIO { + +class UnlinkCore final { +public: + static FsResult DoUnlink(const std::string &src); +}; + +} // namespace ModuleFileIO +} // namespace FileManagement +} // namespace OHOS +#endif // INTERFACES_KITS_JS_SRC_MOD_FS_PROPERTIES_UNLINK_CORE_H \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fs/properties/watcher.cpp b/interfaces/kits/js/src/mod_fs/properties/watcher.cpp index b9fc7eb7428eeafb343ce986128df55f7d061da1..5f9dbef6a36fbb357dca211f771ac22cabfa0e3e 100644 --- a/interfaces/kits/js/src/mod_fs/properties/watcher.cpp +++ b/interfaces/kits/js/src/mod_fs/properties/watcher.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023 Huawei Device Co., Ltd. + * Copyright (c) 2023-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -21,10 +21,11 @@ #include #include +#include "class_watcher/watcher_entity.h" +#include "class_watcher/watcher_n_exporter.h" #include "file_utils.h" #include "filemgmt_libhilog.h" -#include "../class_watcher/watcher_entity.h" -#include "../class_watcher/watcher_n_exporter.h" + namespace OHOS::FileManagement::ModuleFileIO { using namespace std; using namespace OHOS::FileManagement::LibN; diff --git a/interfaces/kits/js/src/mod_fs/properties/write_core.cpp b/interfaces/kits/js/src/mod_fs/properties/write_core.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e99dab6326ea0db64862038f3ba522284921deb9 --- /dev/null +++ b/interfaces/kits/js/src/mod_fs/properties/write_core.cpp @@ -0,0 +1,130 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "write_core.h" + +#include +#include +#include +#include +#include +#include + +#ifdef FILE_API_TRACE +#include "hitrace_meter.h" +#endif + +namespace OHOS { +namespace FileManagement { +namespace ModuleFileIO { +using namespace std; + +static tuple ValidWriteArg( + void *buffer, const size_t bufLen, const optional &options) +{ + size_t retLen = 0; + int64_t offset = -1; + bool succ = false; + + if (bufLen > UINT_MAX) { + HILOGE("The Size of buffer is too large"); + return { false, nullptr, 0, offset }; + } + + optional lengthOp = nullopt; + optional offsetOp = nullopt; + if (options.has_value()) { + WriteOptions op = options.value(); + lengthOp = op.length; + offsetOp = op.offset; + } + + tie(succ, retLen) = FsUtils::GetActualLen(bufLen, 0, lengthOp); + if (!succ) { + HILOGE("Failed to get actual length"); + return { false, nullptr, 0, offset }; + } + + if (offsetOp.has_value()) { + offset = offsetOp.value(); + if (offset < 0) { + HILOGE("option.offset shall be positive number"); + return { false, nullptr, 0, offset }; + } + } + return { true, buffer, retLen, offset }; +} + +FsResult WriteCore::DoWrite(const int32_t fd, const string &buffer, const optional &options) +{ + if (fd < 0) { + HILOGE("Invalid fd from JS first argument"); + return FsResult::Error(EINVAL); + } + + bool succ = false; + size_t len = 0; + int64_t offset = -1; + void *buf = const_cast(static_cast(buffer.c_str())); + size_t bufLen = static_cast(buffer.length()); + + tie(succ, buf, len, offset) = ValidWriteArg(buf, bufLen, options); + if (!succ) { + HILOGE("Failed to resolve buf and options"); + return FsResult::Error(EINVAL); + } + + return DoWrite(fd, buf, len, offset); +} + +FsResult WriteCore::DoWrite(const int32_t fd, const ArrayBuffer &buffer, const optional &options) +{ + if (fd < 0) { + HILOGE("Invalid fd from JS first argument"); + return FsResult::Error(EINVAL); + } + + bool succ = false; + size_t len = 0; + int64_t offset = -1; + void *buf = nullptr; + + tie(succ, buf, len, offset) = ValidWriteArg(buffer.buf, buffer.length, options); + if (!succ) { + HILOGE("Failed to resolve buf and options"); + return FsResult::Error(EINVAL); + } + + return DoWrite(fd, buf, len, offset); +} + +FsResult WriteCore::DoWrite(const int32_t fd, void *buf, const size_t len, const int64_t offset) +{ + uv_buf_t buffer = uv_buf_init(static_cast(buf), static_cast(len)); + unique_ptr writeReq = { new uv_fs_t, FsUtils::FsReqCleanup }; + if (!writeReq) { + return FsResult::Error(ENOMEM); + } + int ret = uv_fs_write(nullptr, writeReq.get(), fd, &buffer, 1, offset, nullptr); + if (ret < 0) { + HILOGE("Failed to write file for %{public}d", ret); + return FsResult::Error(ret); + } + return FsResult::Success(static_cast(ret)); +} + +} // namespace ModuleFileIO +} // namespace FileManagement +} // namespace OHOS \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fs/properties/write_core.h b/interfaces/kits/js/src/mod_fs/properties/write_core.h new file mode 100644 index 0000000000000000000000000000000000000000..f50ae27c856a36f9fa6e15a2884eb4e9d746bf81 --- /dev/null +++ b/interfaces/kits/js/src/mod_fs/properties/write_core.h @@ -0,0 +1,48 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef INTERFACES_KITS_JS_SRC_MOD_FS_PROPERTIES_WRITE_CORE_H +#define INTERFACES_KITS_JS_SRC_MOD_FS_PROPERTIES_WRITE_CORE_H + +#include "filemgmt_libfs.h" +#include "filemgmt_libhilog.h" +#include "fs_utils.h" + +namespace OHOS { +namespace FileManagement { +namespace ModuleFileIO { +using namespace std; + +struct WriteOptions { + optional length = nullopt; + optional offset = nullopt; + optional encoding = nullopt; +}; + +class WriteCore final { +public: + static FsResult DoWrite( + const int32_t fd, const string &buffer, const optional &options = nullopt); + static FsResult DoWrite( + const int32_t fd, const ArrayBuffer &buffer, const optional &options = nullopt); + +private: + static FsResult DoWrite(const int32_t fd, void *buf, const size_t len, const int64_t offset); +}; + +} // namespace ModuleFileIO +} // namespace FileManagement +} // namespace OHOS +#endif // INTERFACES_KITS_JS_SRC_MOD_FS_PROPERTIES_WRITE_CORE_H \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_hash/ani/bind_function_class.cpp b/interfaces/kits/js/src/mod_hash/ani/bind_function_class.cpp new file mode 100644 index 0000000000000000000000000000000000000000..5ab549948f7657e1acd6b2f77b61051469aabf57 --- /dev/null +++ b/interfaces/kits/js/src/mod_hash/ani/bind_function_class.cpp @@ -0,0 +1,60 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include "ani_signature.h" +#include "bind_function.h" +#include "hash_ani.h" + +using namespace OHOS::FileManagement::ModuleFileIO::ANI; +using namespace OHOS::FileManagement::ModuleFileIO::ANI::AniSignature; + +static ani_status BindStaticMethods(ani_env *env) +{ + auto classDesc = Impl::HashImpl::classDesc.c_str(); + std::array methods = { + ani_native_function { "hashSync", nullptr, reinterpret_cast(HashAni::HashSync) }, + }; + return BindClass(env, classDesc, methods); +} + +ANI_EXPORT ani_status ANI_Constructor(ani_vm *vm, uint32_t *result) +{ + if (vm == nullptr) { + HILOGE("Invalid parameter vm"); + return ANI_INVALID_ARGS; + } + + if (result == nullptr) { + HILOGE("Invalid parameter result"); + return ANI_INVALID_ARGS; + } + + ani_env *env; + ani_status status = vm->GetEnv(ANI_VERSION_1, &env); + if (status != ANI_OK) { + HILOGE("Invalid ani version!"); + return ANI_INVALID_VERSION; + } + + status = BindStaticMethods(env); + if (status != ANI_OK) { + HILOGE("Cannot bind native static methods for hash!"); + return status; + }; + + *result = ANI_VERSION_1; + return ANI_OK; +} \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_hash/ani/ets/@ohos.file.hash.ets b/interfaces/kits/js/src/mod_hash/ani/ets/@ohos.file.hash.ets new file mode 100644 index 0000000000000000000000000000000000000000..7b825ee1468b27f428eff144b633d65fe6602dd6 --- /dev/null +++ b/interfaces/kits/js/src/mod_hash/ani/ets/@ohos.file.hash.ets @@ -0,0 +1,93 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { BusinessError, AsyncCallback } from '@ohos.base'; +// import stream from '@ohos.util.stream'; + +export default namespace hash { + export function hash(path: string, algorithm: string): Promise { + return new Promise((resolve: (result: string) => void, reject: (e: BusinessError) => void) => { + let promise = taskpool.execute(HashImpl.hashSync, path, algorithm); + promise.then((ret: NullishType): void => { + let res = ret as string; + resolve(res); + }).catch((e: BusinessError): void => { + reject(e); + }); + }); + } + + export function hash(path: string, algorithm: string, callback: AsyncCallback): void { + let promise = taskpool.execute(HashImpl.hashSync, path, algorithm); + promise.then((ret: NullishType) => { + let e = new BusinessError(); + e.code = 0; + let res = ret as string; + callback(e, res); + }).catch((e: BusinessError): void => { + callback(e, ""); + }); + } + + // export function createHash(algorithm: string): HashStream { + // return new HashStream(algorithm); + // } + + // export class HashStream extends stream.Transform { + // hs: hash.HashStream; + // hashBuf?: ArrayBuffer; + + // constructor(algorithm: string) { + // super(); + // this.hs = new hash.HashStream(algorithm); + // } + + // digest(): string { + // return this.hs.digest(); + // } + + // update(data: ArrayBuffer): void { + // this.hs.update(data); + // } + + // doTransform(chunk: string, encoding: string, callback: () => void): void { + // let charCodes: number[] = []; + // for (let i = 0; i < chunk.length; i++) { + // charCodes = [...charCodes, chunk.charCodeAt(i)]; + // } + // const buf = new Uint8Array(charCodes).buffer; + // this.hs.update((buf as ArrayBuffer)); + // this.push(chunk); + // callback(); + // } + + // doWrite(chunk: string | Uint8Array, encoding: string, callback: () => void): void { + // callback(); + // } + + // doFlush(callback: () => void): void { + // callback(); + // } + // } +} + +class HashImpl { + + static { + loadLibrary("ani_file_hash"); + } + + static native hashSync(path: string, algorithm: string): string; +} diff --git a/interfaces/kits/js/src/mod_hash/ani/hash_ani.cpp b/interfaces/kits/js/src/mod_hash/ani/hash_ani.cpp new file mode 100644 index 0000000000000000000000000000000000000000..6acb4389cdaba7a384403d9e61541fbe9dd6e214 --- /dev/null +++ b/interfaces/kits/js/src/mod_hash/ani/hash_ani.cpp @@ -0,0 +1,68 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "hash_ani.h" + +#include "error_handler.h" +#include "filemgmt_libhilog.h" +#include "hash_core.h" +#include "type_converter.h" + +namespace OHOS { +namespace FileManagement { +namespace ModuleFileIO { +namespace ANI { + +using namespace std; +using namespace OHOS::FileManagement::ModuleFileIO; + +ani_string HashAni::HashSync(ani_env *env, [[maybe_unused]] ani_class clazz, ani_string path, ani_string algorithm) +{ + auto [succPath, srcPath] = TypeConverter::ToUTF8String(env, path); + if (!succPath) { + HILOGE("Invalid path"); + ErrorHandler::Throw(env, EINVAL); + return nullptr; + } + + auto [succAlg, algType] = TypeConverter::ToUTF8String(env, algorithm); + if (!succAlg) { + HILOGE("Invalid algorithm"); + ErrorHandler::Throw(env, EINVAL); + return nullptr; + } + + auto ret = HashCore::DoHash(srcPath, algType); + if (!ret.IsSuccess()) { + HILOGE("DoHash failed"); + const auto &err = ret.GetError(); + ErrorHandler::Throw(env, err); + return nullptr; + } + + const auto &res = ret.GetData().value(); + auto [succ, result] = TypeConverter::ToAniString(env, res); + if (!succ) { + HILOGE("Convert hash value to ani string failed"); + ErrorHandler::Throw(env, UNKNOWN_ERR); + return nullptr; + } + return result; +} + +} // namespace ANI +} // namespace ModuleFileIO +} // namespace FileManagement +} // namespace OHOS \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_hash/ani/hash_ani.h b/interfaces/kits/js/src/mod_hash/ani/hash_ani.h new file mode 100644 index 0000000000000000000000000000000000000000..7b0890fe78e7ad5dbf86a84553300d1736a5d775 --- /dev/null +++ b/interfaces/kits/js/src/mod_hash/ani/hash_ani.h @@ -0,0 +1,36 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef INTERFACES_KITS_JS_SRC_MOD_HASH_PROPERTIES_HASH_ANI_H +#define INTERFACES_KITS_JS_SRC_MOD_HASH_PROPERTIES_HASH_ANI_H + +#include + +namespace OHOS { +namespace FileManagement { +namespace ModuleFileIO { +namespace ANI { + +class HashAni final { +public: + static ani_string HashSync(ani_env *env, [[maybe_unused]] ani_class clazz, ani_string path, ani_string algorithm); +}; + +} // namespace ANI +} // namespace ModuleFileIO +} // namespace FileManagement +} // namespace OHOS + +#endif // INTERFACES_KITS_JS_SRC_MOD_HASH_PROPERTIES_HASH_ANI_H \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_hash/hash_core.cpp b/interfaces/kits/js/src/mod_hash/hash_core.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ed75b4b0cd462c8fef0bc8d76009e7bc32d0fd93 --- /dev/null +++ b/interfaces/kits/js/src/mod_hash/hash_core.cpp @@ -0,0 +1,63 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "hash_core.h" + +#include +#include +#include + +#include "filemgmt_libhilog.h" +#include "hash_file.h" + +namespace OHOS { +namespace FileManagement { +namespace ModuleFileIO { +using namespace std; + +static HASH_ALGORITHM_TYPE GetHashAlgorithm(const string &alg) +{ + return (algorithmMaps.find(alg) != algorithmMaps.end()) ? algorithmMaps.at(alg) : HASH_ALGORITHM_TYPE_UNSUPPORTED; +} + +FsResult HashCore::DoHash(const string &path, const string &algorithm) +{ + HASH_ALGORITHM_TYPE algType = GetHashAlgorithm(algorithm); + if (algType == HASH_ALGORITHM_TYPE_UNSUPPORTED) { + HILOGE("Invalid algoritm"); + return FsResult::Error(EINVAL); + } + + int ret = EIO; + auto arg = make_shared(); + string &res = *arg; + if (algType == HASH_ALGORITHM_TYPE_MD5) { + tie(ret, res) = DistributedFS::HashFile::HashWithMD5(path); + } else if (algType == HASH_ALGORITHM_TYPE_SHA1) { + tie(ret, res) = DistributedFS::HashFile::HashWithSHA1(path); + } else if (algType == HASH_ALGORITHM_TYPE_SHA256) { + tie(ret, res) = DistributedFS::HashFile::HashWithSHA256(path); + } + + if (ret) { + return FsResult::Error(ret); + } + + return FsResult::Success(*arg); +} + +} // namespace ModuleFileIO +} // namespace FileManagement +} // namespace OHOS \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_hash/hash_core.h b/interfaces/kits/js/src/mod_hash/hash_core.h new file mode 100644 index 0000000000000000000000000000000000000000..47119f1ac3e43d512c900cd81b3e8dc2f35e49c0 --- /dev/null +++ b/interfaces/kits/js/src/mod_hash/hash_core.h @@ -0,0 +1,48 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef INTERFACES_KITS_JS_SRC_MOD_HASH_PROPERTIES_HASH_CORE_H +#define INTERFACES_KITS_JS_SRC_MOD_HASH_PROPERTIES_HASH_CORE_H + +#include +#include "filemgmt_libfs.h" + +namespace OHOS { +namespace FileManagement { +namespace ModuleFileIO { + +enum HASH_ALGORITHM_TYPE { + HASH_ALGORITHM_TYPE_MD5, + HASH_ALGORITHM_TYPE_SHA1, + HASH_ALGORITHM_TYPE_SHA256, + HASH_ALGORITHM_TYPE_UNSUPPORTED, +}; + +const std::map algorithmMaps = { + {"md5", HASH_ALGORITHM_TYPE_MD5}, + {"sha1", HASH_ALGORITHM_TYPE_SHA1}, + {"sha256", HASH_ALGORITHM_TYPE_SHA256}, +}; + +class HashCore final { +public: + static FsResult DoHash(const std::string &path, const std::string &algorithm); +}; + +const std::string PROCEDURE_HASH_NAME = "FileIOHash"; +} // namespace ModuleFileIO +} // namespace FileManagement +} // namespace OHOS +#endif // INTERFACES_KITS_JS_SRC_MOD_HASH_PROPERTIES_HASH_CORE_H \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_securitylabel/ani/bind_function_class.cpp b/interfaces/kits/js/src/mod_securitylabel/ani/bind_function_class.cpp new file mode 100644 index 0000000000000000000000000000000000000000..947e460b65992a5ec8c5042a6dd205d03ef42c56 --- /dev/null +++ b/interfaces/kits/js/src/mod_securitylabel/ani/bind_function_class.cpp @@ -0,0 +1,63 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include "ani_signature.h" +#include "bind_function.h" +#include "securitylabel_ani.h" + +using namespace OHOS::FileManagement::ModuleFileIO::ANI; +using namespace OHOS::FileManagement::ModuleFileIO::ANI::AniSignature; + +static ani_status BindStaticMethods(ani_env *env) +{ + auto classDesc = Impl::SecurityLabelImpl::classDesc.c_str(); + std::array methods = { + ani_native_function { + "setSecurityLabelSync", nullptr, reinterpret_cast(SecurityLabelAni::SetSecurityLabelSync) }, + ani_native_function { + "getSecurityLabelSync", nullptr, reinterpret_cast(SecurityLabelAni::GetSecurityLabelSync) }, + }; + return BindClass(env, classDesc, methods); +} + +ANI_EXPORT ani_status ANI_Constructor(ani_vm *vm, uint32_t *result) +{ + if (vm == nullptr) { + HILOGE("Invalid parameter vm"); + return ANI_INVALID_ARGS; + } + + if (result == nullptr) { + HILOGE("Invalid parameter result"); + return ANI_INVALID_ARGS; + } + + ani_env *env; + ani_status status = vm->GetEnv(ANI_VERSION_1, &env); + if (status != ANI_OK) { + HILOGE("Invalid ani version!"); + return ANI_INVALID_VERSION; + } + + status = BindStaticMethods(env); + if (status != ANI_OK) { + HILOGE("Cannot bind native static methods for securitylabel!"); + return status; + }; + + *result = ANI_VERSION_1; + return ANI_OK; +} diff --git a/interfaces/kits/js/src/mod_securitylabel/ani/ets/@ohos.file.securityLabel.ets b/interfaces/kits/js/src/mod_securitylabel/ani/ets/@ohos.file.securityLabel.ets new file mode 100644 index 0000000000000000000000000000000000000000..06e659dc275ae1890e009c02fc830bd8e766dbea --- /dev/null +++ b/interfaces/kits/js/src/mod_securitylabel/ani/ets/@ohos.file.securityLabel.ets @@ -0,0 +1,86 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { BusinessError, AsyncCallback } from '@ohos.base'; + +namespace securityLabel { + export type DataLevel = 's0' | 's1' | 's2' | 's3' | 's4'; + + export function setSecurityLabel(path: string, type: DataLevel): Promise { + return new Promise((resolve: (result: undefined) => void, reject: (e: BusinessError) => void): void => { + let promise = taskpool.execute((path: string, type: DataLevel): void => SecurityLabelImpl.setSecurityLabelSync(path, type), path, type); + promise.then((ret: NullishType): void => { + resolve(undefined); + }).catch((e: BusinessError): void => { + reject(e); + }); + }); + } + + export function setSecurityLabel(path: string, type: DataLevel, callback: AsyncCallback): void { + let promise = taskpool.execute((path: string, type: DataLevel): void => SecurityLabelImpl.setSecurityLabelSync(path, type), path, type); + promise.then((ret: NullishType): void => { + let e = new BusinessError(); + e.code = 0; + callback(e, undefined); + }).catch((e: BusinessError): void => { + callback(e, undefined); + }); + } + + export function setSecurityLabelSync(path: string, type: DataLevel): void { + return SecurityLabelImpl.setSecurityLabelSync(path, type); + } + + export function getSecurityLabel(path: string): Promise { + return new Promise((resolve: (result: string) => void, reject: (e: BusinessError) => void): void => { + let promise = taskpool.execute((path: string): string => SecurityLabelImpl.getSecurityLabelSync(path), path); + promise.then((ret: NullishType): void => { + let r = ret as string; + resolve(r); + }).catch((e: BusinessError): void => { + reject(e); + }); + }); + } + + export function getSecurityLabel(path: string, callback: AsyncCallback): void { + let promise = taskpool.execute((path: string): string => SecurityLabelImpl.getSecurityLabelSync(path), path); + promise.then((ret: NullishType): void => { + let e = new BusinessError(); + e.code = 0; + let r = ret as string; + callback(e, r); + }).catch((e: BusinessError): void => { + callback(e, ""); + }); + } + + export function getSecurityLabelSync(path: string): string { + return SecurityLabelImpl.getSecurityLabelSync(path); + } +} + +export default securityLabel; + +class SecurityLabelImpl { + + static { + loadLibrary("ani_file_securitylabel"); + } + + static native setSecurityLabelSync(path: string, type: securityLabel.DataLevel): void; + static native getSecurityLabelSync(path: string): string; +} diff --git a/interfaces/kits/js/src/mod_securitylabel/ani/securitylabel_ani.cpp b/interfaces/kits/js/src/mod_securitylabel/ani/securitylabel_ani.cpp new file mode 100644 index 0000000000000000000000000000000000000000..4d6fd2b3211890d4e1092c8925da40bddbe0269f --- /dev/null +++ b/interfaces/kits/js/src/mod_securitylabel/ani/securitylabel_ani.cpp @@ -0,0 +1,89 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "securitylabel_ani.h" + +#include "error_handler.h" +#include "filemgmt_libhilog.h" +#include "securitylabel_core.h" +#include "type_converter.h" + +namespace OHOS { +namespace FileManagement { +namespace ModuleFileIO { +namespace ANI { + +using namespace std; +using namespace OHOS::FileManagement::ModuleFileIO; +using namespace OHOS::FileManagement::ModuleSecurityLabel; + +void SecurityLabelAni::SetSecurityLabelSync( + ani_env *env, [[maybe_unused]] ani_class clazz, ani_string path, ani_string level) +{ + auto [succPath, srcPath] = TypeConverter::ToUTF8String(env, path); + if (!succPath) { + HILOGE("Invalid path"); + ErrorHandler::Throw(env, EINVAL); + return; + } + + auto [succLevel, dataLevel] = TypeConverter::ToUTF8String(env, level); + if (!succLevel) { + HILOGE("Invalid dataLevel"); + ErrorHandler::Throw(env, EINVAL); + return; + } + + auto ret = DoSetSecurityLabel(srcPath, dataLevel); + if (!ret.IsSuccess()) { + HILOGE("Set securitylabel failed"); + const auto &err = ret.GetError(); + ErrorHandler::Throw(env, err); + return; + } +} + +ani_string SecurityLabelAni::GetSecurityLabelSync(ani_env *env, [[maybe_unused]] ani_class clazz, ani_string path) +{ + auto [succPath, srcPath] = TypeConverter::ToUTF8String(env, path); + if (!succPath) { + HILOGE("Invalid path"); + ErrorHandler::Throw(env, EINVAL); + return nullptr; + } + + auto ret = DoGetSecurityLabel(srcPath); + if (!ret.IsSuccess()) { + HILOGE("Get securitylabel failed"); + const auto &err = ret.GetError(); + ErrorHandler::Throw(env, err); + return nullptr; + } + + string res = ret.GetData().value(); + auto [succ, result] = TypeConverter::ToAniString(env, res); + if (!succ) { + HILOGE("Create ani_string error"); + ErrorHandler::Throw(env, UNKNOWN_ERR); + return nullptr; + } + + return result; +} + +} // namespace ANI +} // namespace ModuleFileIO +} // namespace FileManagement +} // namespace OHOS \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_securitylabel/ani/securitylabel_ani.h b/interfaces/kits/js/src/mod_securitylabel/ani/securitylabel_ani.h new file mode 100644 index 0000000000000000000000000000000000000000..8bb5741c9c347700ded871b900efc44297c823d9 --- /dev/null +++ b/interfaces/kits/js/src/mod_securitylabel/ani/securitylabel_ani.h @@ -0,0 +1,37 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef SECURITYLABEL_ANI_H +#define SECURITYLABEL_ANI_H + +#include + +namespace OHOS { +namespace FileManagement { +namespace ModuleFileIO { +namespace ANI { + +class SecurityLabelAni final { +public: + static void SetSecurityLabelSync(ani_env *env, [[maybe_unused]] ani_class clazz, ani_string path, ani_string level); + static ani_string GetSecurityLabelSync(ani_env *env, [[maybe_unused]] ani_class clazz, ani_string path); +}; + +} // namespace ANI +} // namespace ModuleFileIO +} // namespace FileManagement +} // namespace OHOS + +#endif // SECURITYLABEL_ANI_H \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_securitylabel/securitylabel_core.cpp b/interfaces/kits/js/src/mod_securitylabel/securitylabel_core.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d68002e8aa8ddcab3863ebed88d44bcc22d1fa13 --- /dev/null +++ b/interfaces/kits/js/src/mod_securitylabel/securitylabel_core.cpp @@ -0,0 +1,48 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "securitylabel_core.h" + +#include "filemgmt_libhilog.h" +#include "security_label.h" + +namespace OHOS { +namespace FileManagement { +namespace ModuleSecurityLabel { +using namespace std; +FsResult DoSetSecurityLabel(const string &path, const string &dataLevel) +{ + if (DATA_LEVEL.find(dataLevel) == DATA_LEVEL.end()) { + HILOGE("Invalid Argument of dataLevelEnum"); + return FsResult::Error(EINVAL); + } + + bool ret = SecurityLabel::SetSecurityLabel(path, dataLevel); + if (!ret) { + return FsResult::Error(errno); + } + + return FsResult::Success(); +} + +FsResult DoGetSecurityLabel(const string &path) +{ + string ret = SecurityLabel::GetSecurityLabel(path); + return FsResult::Success(move(ret)); +} + +} // namespace ModuleSecurityLabel +} // namespace FileManagement +} // namespace OHOS \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_securitylabel/securitylabel_core.h b/interfaces/kits/js/src/mod_securitylabel/securitylabel_core.h new file mode 100644 index 0000000000000000000000000000000000000000..cb7766eaf5a6087c1e449e2077046ee4a63a9f33 --- /dev/null +++ b/interfaces/kits/js/src/mod_securitylabel/securitylabel_core.h @@ -0,0 +1,32 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef SECURITYLABEL_CORE_H +#define SECURITYLABEL_CORE_H + +#include "filemgmt_libfs.h" + +namespace OHOS { +namespace FileManagement { +namespace ModuleSecurityLabel { +using namespace ModuleFileIO; + +FsResult DoSetSecurityLabel(const string &path, const string &dataLevel); +FsResult DoGetSecurityLabel(const string &path); + +} // namespace ModuleSecurityLabel +} // namespace FileManagement +} // namespace OHOS +#endif // SECURITYLABEL_CORE_H \ No newline at end of file diff --git a/interfaces/kits/native/BUILD.gn b/interfaces/kits/native/BUILD.gn index 37a3a3f4204aec6f5b2bc16a6c24ccaafb3ba452..57a18d791685b0300da28dc82a51bced4c7675de 100644 --- a/interfaces/kits/native/BUILD.gn +++ b/interfaces/kits/native/BUILD.gn @@ -1,4 +1,4 @@ -# Copyright (c) 2022-2024 Huawei Device Co., Ltd. +# Copyright (c) 2022-2025 Huawei Device Co., Ltd. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at @@ -186,6 +186,7 @@ ohos_shared_library("fileio_native") { "ability_base:zuri", "app_file_service:fileuri_native", "bounds_checking_function:libsec_shared", + "c_utils:utils", "hilog:libhilog", ] innerapi_tags = [ "platformsdk" ] diff --git a/interfaces/kits/native/task_signal/task_signal.cpp b/interfaces/kits/native/task_signal/task_signal.cpp index 3ff5eb434e62bb27c23d370d7bf9c0b9dc027900..cf0fd9d174baa1992436b4945cdd7806f7f42da7 100644 --- a/interfaces/kits/native/task_signal/task_signal.cpp +++ b/interfaces/kits/native/task_signal/task_signal.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2024 Huawei Device Co., Ltd. + * Copyright (c) 2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -27,18 +27,18 @@ int32_t TaskSignal::Cancel() { HILOGD("TaskSignal Cancel in."); if (dfsCopyTask_.load()) { - auto ret = Storage::DistributedFile::FileCopyManager::GetInstance()->Cancel(srcUri_, dstUri_); + auto ret = Storage::DistributedFile::FileCopyManager::GetInstance()->Cancel(srcUri_, dstUri_, true); if (ret != 0) { HILOGE("Cancel failed, ret = %{public}d", ret); return ret; } OnCancel(); return ret; - } + } if (remoteTask_.load()) { int32_t ret = 0; if (sessionName_.empty()) { - ret = Storage::DistributedFile::FileCopyManager::GetInstance()->Cancel(srcUri_, dstUri_); + ret = Storage::DistributedFile::FileCopyManager::GetInstance()->Cancel(srcUri_, dstUri_, true); } else { ret = Storage::DistributedFile::DistributedFileDaemonManager::GetInstance(). CancelCopyTask(sessionName_); diff --git a/interfaces/kits/rust/BUILD.gn b/interfaces/kits/rust/BUILD.gn index 965a4ec2138a9353e605c806118cb3e4eadf85d5..afaa3df582d38d2d1ef0974bf6a9463afeec75b3 100644 --- a/interfaces/kits/rust/BUILD.gn +++ b/interfaces/kits/rust/BUILD.gn @@ -14,7 +14,7 @@ import("//build/ohos.gni") config("public_config") { - include_dirs = [ "include/rust_file.h" ] + include_dirs = [ "./include" ] } ohos_rust_shared_ffi("rust_file") { @@ -24,8 +24,15 @@ ohos_rust_shared_ffi("rust_file") { sources = [ "src/lib.rs" ] crate_name = "rust_file" rustflags = [ "-Zstack-protector=all" ] - deps = [ "//third_party/rust/crates/libc:lib" ] + deps = [] external_deps = [ "hilog:hilog_rust" ] + + if (defined(global_parts_info) && !defined(global_parts_info.third_party_rust_libc)) { + deps += [ "//third_party/rust/crates/libc:lib" ] + } else { + external_deps += [ "rust_libc:lib" ] + } + innerapi_tags = [ "platformsdk" ] public_configs = [ ":public_config" ] } diff --git a/interfaces/kits/ts/gen_obj.gni b/interfaces/kits/ts/gen_obj.gni index ba5c656dcd08934cfd95b86f45160ecdecf5c280..793707e37102857a60cce2c266bec435c342ab07 100644 --- a/interfaces/kits/ts/gen_obj.gni +++ b/interfaces/kits/ts/gen_obj.gni @@ -1,4 +1,4 @@ -# Copyright (c) 2024 Huawei Device Co., Ltd. +# Copyright (c) 2024-2025 Huawei Device Co., Ltd. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at @@ -14,7 +14,6 @@ import("//build/config/clang/clang.gni") import("//build/ohos.gni") -ace_root = "//foundation/arkui/ace_engine" is_ohos_standard_system = is_standard_system && !is_arkui_x use_mingw_win = "${current_os}_${current_cpu}" == "mingw_x86_64" use_mac = "${current_os}_${current_cpu}" == "mac_x64" || @@ -53,19 +52,19 @@ template("gen_obj") { if (use_mingw_win) { objcopy_tool = objcopy_mingw - script = "$ace_root/build/tools/build_resource_to_bytecode.py" + script = "//build/config/components/ace_engine/build_resource_to_bytecode.py" } else if (use_mac || target_os == "ios") { objcopy_tool = objcopy_clang - script = "$ace_root/build/tools/build_resource_to_bytecode.py" + script = "//build/config/components/ace_engine/build_resource_to_bytecode.py" } else if (use_linux) { objcopy_tool = objcopy_x86_64 - script = "$ace_root/build/tools/build_resource_to_bytecode.py" + script = "//build/config/components/ace_engine/build_resource_to_bytecode.py" } else if (target_cpu == "x86_64") { objcopy_tool = objcopy_x86_64 - script = "$ace_root/build/tools/run_objcopy.py" + script = "//build/scripts/run_objcopy.py" } else { objcopy_tool = objcopy_default - script = "$ace_root/build/tools/run_objcopy.py" + script = "//build/scripts/run_objcopy.py" } args = [ diff --git a/interfaces/kits/ts/streamhash/BUILD.gn b/interfaces/kits/ts/streamhash/BUILD.gn index a27f83fe40d7468814d783f25737a9c809742dc2..4b67ec4e38ec5b5483f4d45f49ae0362b37bd489 100644 --- a/interfaces/kits/ts/streamhash/BUILD.gn +++ b/interfaces/kits/ts/streamhash/BUILD.gn @@ -1,4 +1,4 @@ -# Copyright (c) 2024 Huawei Device Co., Ltd. +# Copyright (c) 2024-2025 Huawei Device Co., Ltd. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at @@ -11,7 +11,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -import("//arkcompiler/ets_frontend/es2panda/es2abc_config.gni") +import("//build/config/components/ets_frontend/es2abc_config.gni") import("//foundation/filemanagement/file_api/file_api.gni") import("//foundation/filemanagement/file_api/interfaces/kits/ts/gen_obj.gni") @@ -130,5 +130,5 @@ ohos_source_set("streamhash_static") { } group("streamhash_packages") { - public_deps = [ ":streamhash" ] + deps = [ ":streamhash" ] } diff --git a/interfaces/kits/ts/streamrw/BUILD.gn b/interfaces/kits/ts/streamrw/BUILD.gn index a2eece6f1e1fc76675d23f65978db63d43078a99..be4fab7321791ddecc630b526f93f896a865bc4d 100644 --- a/interfaces/kits/ts/streamrw/BUILD.gn +++ b/interfaces/kits/ts/streamrw/BUILD.gn @@ -1,4 +1,4 @@ -# Copyright (c) 2024 Huawei Device Co., Ltd. +# Copyright (c) 2024-2025 Huawei Device Co., Ltd. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at @@ -11,7 +11,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -import("//arkcompiler/ets_frontend/es2panda/es2abc_config.gni") +import("//build/config/components/ets_frontend/es2abc_config.gni") import("//foundation/filemanagement/file_api/file_api.gni") import("//foundation/filemanagement/file_api/interfaces/kits/ts/gen_obj.gni") @@ -130,5 +130,5 @@ ohos_source_set("streamrw_static") { } group("streamrw_packages") { - public_deps = [ ":streamrw" ] + deps = [ ":streamrw" ] } diff --git a/interfaces/test/unittest/BUILD.gn b/interfaces/test/unittest/BUILD.gn index ad60f3a1211394a32365a2579f6f3d23e668c112..5aeda1645edd88a73d1107d5e434d2f809a486a6 100644 --- a/interfaces/test/unittest/BUILD.gn +++ b/interfaces/test/unittest/BUILD.gn @@ -1,4 +1,4 @@ -# Copyright (c) 2022-2023 Huawei Device Co., Ltd. +# Copyright (c) 2022-2025 Huawei Device Co., Ltd. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at @@ -13,11 +13,15 @@ import("//foundation/filemanagement/file_api/file_api.gni") -group("unittest") { +group("file_api_unittest") { testonly = true deps = [ "class_file:class_file_test", "filemgmt_libn_test:filemgmt_libn_test", + "js:ani_file_fs_mock_test", + "js:ani_file_fs_test", + "js:ani_file_hash_test", + "js:ani_file_securitylabel_test", "remote_uri:remote_uri_test", "task_signal:task_signal_test", ] diff --git a/interfaces/test/unittest/class_file/BUILD.gn b/interfaces/test/unittest/class_file/BUILD.gn index 535c6f5b5a19562bf3bd9d07fb2d50c5e214cfc7..b2bacc89db97993c618754ab7fea989a732b49b0 100644 --- a/interfaces/test/unittest/class_file/BUILD.gn +++ b/interfaces/test/unittest/class_file/BUILD.gn @@ -1,4 +1,4 @@ -# Copyright (c) 2023 Huawei Device Co., Ltd. +# Copyright (c) 2023-2025 Huawei Device Co., Ltd. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at @@ -23,8 +23,7 @@ ohos_unittest("class_file_test") { include_dirs = [ "${file_api_path}/interfaces/kits/rust/include" ] - deps = [ - "${file_api_path}/interfaces/kits/rust:rust_file", - "//third_party/googletest:gtest_main", - ] + deps = [ "${file_api_path}/interfaces/kits/rust:rust_file" ] + + external_deps = [ "googletest:gtest_main" ] } diff --git a/interfaces/test/unittest/filemgmt_libn_test/BUILD.gn b/interfaces/test/unittest/filemgmt_libn_test/BUILD.gn index ea20a1cf9f7b571e107d8d534852829741ebf3bb..bd8ecb3473fe0148ce528f163db2a7f9c3388e7e 100644 --- a/interfaces/test/unittest/filemgmt_libn_test/BUILD.gn +++ b/interfaces/test/unittest/filemgmt_libn_test/BUILD.gn @@ -1,4 +1,4 @@ -# Copyright (C) 2023 Huawei Device Co., Ltd. +# Copyright (C) 2023-2025 Huawei Device Co., Ltd. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at @@ -28,13 +28,13 @@ ohos_unittest("filemgmt_libn_test") { deps = [ "${utils_path}/filemgmt_libhilog:filemgmt_libhilog", "${utils_path}/filemgmt_libn:filemgmt_libn", - "//third_party/googletest:gtest_main", ] external_deps = [ "access_token:libaccesstoken_sdk", "c_utils:utils", "c_utils:utilsbase", + "googletest:gtest_main", "hilog:libhilog", "ipc:ipc_core", "napi:ace_napi", diff --git a/interfaces/test/unittest/hyperaio/BUILD.gn b/interfaces/test/unittest/hyperaio/BUILD.gn index af73bb55d568443fc8d7842abc05d5ab16a8bcbf..d5c17c97b196306f4e8949db13abf5837e49e45e 100644 --- a/interfaces/test/unittest/hyperaio/BUILD.gn +++ b/interfaces/test/unittest/hyperaio/BUILD.gn @@ -19,7 +19,11 @@ ohos_unittest("hyperaio_test") { resource_config_file = "../resource/ohos_test.xml" - sources = [ "hyperaio_test.cpp" ] + sources = [ + "hyperaio_test.cpp", + "${file_api_path}/interfaces/kits/hyperaio/src/hyperaio.cpp", + "${file_api_path}/interfaces/kits/hyperaio/src/hyperaio_trace.cpp" + ] include_dirs = [ "include", @@ -27,7 +31,6 @@ ohos_unittest("hyperaio_test") { ] deps = [ - "${file_api_path}/interfaces/kits/hyperaio:HyperAio", ] external_deps = [ @@ -35,9 +38,14 @@ ohos_unittest("hyperaio_test") { "c_utils:utils", "c_utils:utilsbase", "ipc:ipc_core", + "hilog:libhilog", "googletest:gtest_main", + "hitrace:hitrace_meter" + ] + defines = [ + "private = public" ] if (file_api_feature_hyperaio) { - external_deps += [ "liburing:liburing" ] + defines += [ "HYPERAIO_USE_LIBURING" ] } } diff --git a/interfaces/test/unittest/hyperaio/hyperaio_test.cpp b/interfaces/test/unittest/hyperaio/hyperaio_test.cpp index 91ca75c8d26b3be448044c93157250bbf7d5d249..b1916adbd090218beea36cd19246248bff1b1a05 100644 --- a/interfaces/test/unittest/hyperaio/hyperaio_test.cpp +++ b/interfaces/test/unittest/hyperaio/hyperaio_test.cpp @@ -17,12 +17,13 @@ #include #include #include - +#include "liburing.h" #include "hyperaio.h" -namespace { +namespace OHOS::HyperAio { using namespace std; - using namespace OHOS::HyperAio; + using namespace testing; + class HyperAioTest : public testing::Test { public: static void SetUpTestCase(void) {}; @@ -33,29 +34,137 @@ namespace { #ifdef HYPERAIO_USE_LIBURING const uint64_t userData = 12345; const uint32_t len = 1024; - std::function)> callBack = [](std::unique_ptr response) { + const uint32_t batchSize = 300; + const uint32_t Threshold = 600; + HyperAio::ProcessIoResultCallBack callBack = [](std::unique_ptr response) { GTEST_LOG_(INFO) << "HyperAioTest callBack"; }; /** - * @tc.name: HyperAio_StartOpenReqs_0000 - * @tc.desc: Test function of StartOpenReqs() interface for SUCCESS. + * @tc.name: HyperAio_SupportIouring_0000 + * @tc.desc: Test function of SupportIouring() interface for SUCCESS. * @tc.size: MEDIUM * @tc.type: FUNC * @tc.level Level 1 - * @tc.require: AR000HG8M4 */ - HWTEST_F(HyperAioTest, HyperAio_StartOpenReqs_0000, testing::ext::TestSize.Level1) + HWTEST_F(HyperAioTest, HyperAio_SupportIouring_0000, testing::ext::TestSize.Level1) { - GTEST_LOG_(INFO) << "HyperAioTest-begin HyperAio_StartOpenReqs_0000"; + GTEST_LOG_(INFO) << "HyperAioTest-begin HyperAio_SupportIouring_0000"; std::unique_ptr hyperAio_ = std::make_unique(); int32_t result = hyperAio_->SupportIouring(); EXPECT_EQ((result & IOURING_APP_PERMISSION) == 0, true); if ((result & IOURING_APP_PERMISSION) == 0) { return; } - result = hyperAio_->CtxInit(nullptr); + GTEST_LOG_(INFO) << "HyperAioTest-end HyperAio_SupportIouring_0000"; + } + + /** + * @tc.name: HyperAio_CtxInit_0000 + * @tc.desc: Test function of CtxInit() interface for SUCCESS. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ + HWTEST_F(HyperAioTest, HyperAio_CtxInit_0000, testing::ext::TestSize.Level0) + { + GTEST_LOG_(INFO) << "HyperAioTest-begin HyperAio_CtxInit_0000"; + std::unique_ptr hyperAio_ = std::make_unique(); + int32_t result = hyperAio_->CtxInit(&callBack); + EXPECT_EQ(result, 0); + result = hyperAio_->CtxInit(&callBack); + hyperAio_->stopThread_.store(true); + EXPECT_EQ(result, 0); + hyperAio_->DestroyCtx(); + GTEST_LOG_(INFO) << "HyperAioTest-end HyperAio_CtxInit_0000"; + } + + /** + * @tc.name: HyperAio_CtxInit_0001 + * @tc.desc: Test function of CtxInit() interface for SUCCESS. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ + HWTEST_F(HyperAioTest, HyperAio_CtxInit_0001, testing::ext::TestSize.Level1) + { + GTEST_LOG_(INFO) << "HyperAioTest-begin HyperAio_CtxInit_0001"; + std::unique_ptr hyperAio_ = std::make_unique(); + int32_t result = hyperAio_->CtxInit(nullptr); EXPECT_EQ(result, -EINVAL); + GTEST_LOG_(INFO) << "HyperAioTest-end HyperAio_CtxInit_0001"; + } + + /** + * @tc.name: HyperAio_CtxInit_0002 + * @tc.desc: Test function of CtxInit() interface for SUCCESS. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ + HWTEST_F(HyperAioTest, HyperAio_CtxInit_0002, testing::ext::TestSize.Level1) + { + GTEST_LOG_(INFO) << "HyperAioTest-begin HyperAio_CtxInit_0002"; + std::unique_ptr hyperAio_ = std::make_unique(); + int32_t result = hyperAio_->CtxInit(&callBack); + EXPECT_EQ(result, 0); + hyperAio_->DestroyCtx(); + GTEST_LOG_(INFO) << "HyperAioTest-end HyperAio_CtxInit_0002"; + } + + /** + * @tc.name: HyperAio_CtxInit_0003 + * @tc.desc: Test function of CtxInit() interface for SUCCESS. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ + HWTEST_F(HyperAioTest, HyperAio_CtxInit_0003, testing::ext::TestSize.Level1) + { + GTEST_LOG_(INFO) << "HyperAioTest-begin HyperAio_CtxInit_0003"; + std::unique_ptr hyperAio_ = std::make_unique(); + int32_t result = hyperAio_->CtxInit(nullptr); + EXPECT_EQ(result, -EINVAL); + result = hyperAio_->CtxInit(&callBack); + EXPECT_EQ(result, 0); + hyperAio_->DestroyCtx(); + GTEST_LOG_(INFO) << "HyperAioTest-end HyperAio_CtxInit_0003"; + } + + /** + * @tc.name: HyperAio_CtxInit_0004 + * @tc.desc: Test function of CtxInit() interface for SUCCESS. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ + HWTEST_F(HyperAioTest, HyperAio_CtxInit_0004, testing::ext::TestSize.Level1) + { + GTEST_LOG_(INFO) << "HyperAioTest-begin HyperAio_CtxInit_0004"; + std::unique_ptr hyperAio_ = std::make_unique(); + init_flag = false; + int32_t result = hyperAio_->CtxInit(&callBack); + EXPECT_EQ(result, -1); + init_flag = true; + GTEST_LOG_(INFO) << "HyperAioTest-end HyperAio_CtxInit_0004"; + } + + /** + * @tc.name: HyperAio_StartOpenReqs_0000 + * @tc.desc: Test function of StartOpenReqs() interface for SUCCESS. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ + HWTEST_F(HyperAioTest, HyperAio_StartOpenReqs_0000, testing::ext::TestSize.Level1) + { + GTEST_LOG_(INFO) << "HyperAioTest-begin HyperAio_StartOpenReqs_0000"; + std::unique_ptr hyperAio_ = std::make_unique(); + int32_t result = hyperAio_->CtxInit(&callBack); + EXPECT_EQ(result, 0); + result = hyperAio_->StartOpenReqs(nullptr); + EXPECT_EQ(result, -EINVAL); + hyperAio_->DestroyCtx(); GTEST_LOG_(INFO) << "HyperAioTest-end HyperAio_StartOpenReqs_0000"; } @@ -65,23 +174,19 @@ namespace { * @tc.size: MEDIUM * @tc.type: FUNC * @tc.level Level 1 - * @tc.require: AR000HG8M4 */ HWTEST_F(HyperAioTest, HyperAio_StartOpenReqs_0001, testing::ext::TestSize.Level1) { GTEST_LOG_(INFO) << "HyperAioTest-begin HyperAio_StartOpenReqs_0001"; std::unique_ptr hyperAio_ = std::make_unique(); - int32_t result = hyperAio_->SupportIouring(); - EXPECT_EQ((result & IOURING_APP_PERMISSION) == 0, true); - if ((result & IOURING_APP_PERMISSION) == 0) { - return; - } - result = hyperAio_->CtxInit(&callBack); + int32_t result = hyperAio_->CtxInit(&callBack); EXPECT_EQ(result, 0); + hyperAio_->initialized_.store(false); OpenInfo openInfo = {0, O_RDWR, 0, nullptr, userData}; OpenReqs openReqs = {1, &openInfo}; result = hyperAio_->StartOpenReqs(&openReqs); - EXPECT_EQ(result, 0); + EXPECT_EQ(result, -EPERM); + hyperAio_->initialized_.store(true); result = hyperAio_->DestroyCtx(); EXPECT_EQ(result, 0); GTEST_LOG_(INFO) << "HyperAioTest-end HyperAio_StartOpenReqs_0001"; @@ -93,43 +198,115 @@ namespace { * @tc.size: MEDIUM * @tc.type: FUNC * @tc.level Level 1 - * @tc.require: AR000HG8M4 */ - HWTEST_F(HyperAioTest, HyperAio_StartOpenReqs_0002, testing::ext::TestSize.Level1) + HWTEST_F(HyperAioTest, HyperAio_StartOpenReqs_0002, testing::ext::TestSize.Level0) { GTEST_LOG_(INFO) << "HyperAioTest-begin HyperAio_StartOpenReqs_0002"; std::unique_ptr hyperAio_ = std::make_unique(); - int32_t result = hyperAio_->SupportIouring(); - EXPECT_EQ((result & IOURING_APP_PERMISSION) == 0, true); - if ((result & IOURING_APP_PERMISSION) == 0) { - return; - } + int32_t result = hyperAio_->CtxInit(&callBack); + EXPECT_EQ(result, 0); OpenInfo openInfo = {0, O_RDWR, 0, nullptr, userData}; OpenReqs openReqs = {1, &openInfo}; result = hyperAio_->StartOpenReqs(&openReqs); - EXPECT_EQ(result, -EPERM); + EXPECT_EQ(result, 0); + result = hyperAio_->DestroyCtx(); + EXPECT_EQ(result, 0); GTEST_LOG_(INFO) << "HyperAioTest-end HyperAio_StartOpenReqs_0002"; } + /** + * @tc.name: HyperAio_StartOpenReqs_0003 + * @tc.desc: Test function of StartOpenReqs() interface for SUCCESS. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ + HWTEST_F(HyperAioTest, HyperAio_StartOpenReqs_0003, testing::ext::TestSize.Level1) + { + GTEST_LOG_(INFO) << "HyperAioTest-begin HyperAio_StartOpenReqs_0003"; + std::unique_ptr hyperAio_ = std::make_unique(); + int32_t result = hyperAio_->CtxInit(&callBack); + EXPECT_EQ(result, 0); + auto openInfos = std::make_unique(batchSize); + for (int i = 0; i < batchSize; ++i) { + openInfos[i].dfd = 0; + openInfos[i].flags = O_RDWR; + openInfos[i].mode = 0; + openInfos[i].path = nullptr; + openInfos[i].userData = userData + i; + } + OpenReqs openReqs = {batchSize, openInfos.get()}; + result = hyperAio_->StartOpenReqs(&openReqs); + EXPECT_EQ(result, 0); + sqe_flag = false; + result = hyperAio_->StartOpenReqs(&openReqs); + EXPECT_EQ(result, -ENOMEM); + sqe_flag = true; + result = hyperAio_->DestroyCtx(); + EXPECT_EQ(result, 0); + GTEST_LOG_(INFO) << "HyperAioTest-end HyperAio_StartOpenReqs_0003"; + } + + /** + * @tc.name: HyperAio_StartOpenReqs_0004 + * @tc.desc: Test function of StartOpenReqs() interface for SUCCESS. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ + HWTEST_F(HyperAioTest, HyperAio_StartOpenReqs_0004, testing::ext::TestSize.Level1) + { + GTEST_LOG_(INFO) << "HyperAioTest-begin HyperAio_StartOpenReqs_0004"; + std::unique_ptr hyperAio_ = std::make_unique(); + int32_t result = hyperAio_->CtxInit(&callBack); + EXPECT_EQ(result, 0); + auto openInfos = std::make_unique(Threshold); + for (int i = 0; i < Threshold; ++i) { + openInfos[i].dfd = 0; + openInfos[i].flags = O_RDWR; + openInfos[i].mode = 0; + openInfos[i].path = nullptr; + openInfos[i].userData = userData + i; + } + OpenReqs openReqs = {Threshold, openInfos.get()}; + result = hyperAio_->StartOpenReqs(&openReqs); + EXPECT_EQ(result, -EINVAL); + result = hyperAio_->DestroyCtx(); + EXPECT_EQ(result, 0); + GTEST_LOG_(INFO) << "HyperAioTest-end HyperAio_StartOpenReqs_0004"; + } + + /** + * @tc.name: HyperAio_StartOpenReqs_0005 + * @tc.desc: Test function of StartOpenReqs() interface for SUCCESS. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ + HWTEST_F(HyperAioTest, HyperAio_StartOpenReqs_0005, testing::ext::TestSize.Level1) + { + GTEST_LOG_(INFO) << "HyperAioTest-begin HyperAio_StartOpenReqs_0005"; + std::unique_ptr hyperAio_ = std::make_unique(); + int32_t result = hyperAio_->StartOpenReqs(nullptr); + EXPECT_EQ(result, -EINVAL); + GTEST_LOG_(INFO) << "HyperAioTest-end HyperAio_StartOpenReqs_0005"; + } + /** * @tc.name: HyperAio_StartReadReqs_0000 * @tc.desc: Test function of StartReadReqs() interface for SUCCESS. * @tc.size: MEDIUM * @tc.type: FUNC * @tc.level Level 1 - * @tc.require: AR000HG8M4 */ HWTEST_F(HyperAioTest, HyperAio_StartReadReqs_0000, testing::ext::TestSize.Level1) { GTEST_LOG_(INFO) << "HyperAioTest-begin HyperAio_StartReadReqs_0000"; std::unique_ptr hyperAio_ = std::make_unique(); - int32_t result = hyperAio_->SupportIouring(); - EXPECT_EQ((result & IOURING_APP_PERMISSION) == 0, true); - if ((result & IOURING_APP_PERMISSION) == 0) { - return; - } - result = hyperAio_->CtxInit(nullptr); + int32_t result = hyperAio_->CtxInit(&callBack); + result = hyperAio_->StartReadReqs(nullptr); EXPECT_EQ(result, -EINVAL); + result = hyperAio_->DestroyCtx(); GTEST_LOG_(INFO) << "HyperAioTest-end HyperAio_StartReadReqs_0000"; } @@ -139,23 +316,19 @@ namespace { * @tc.size: MEDIUM * @tc.type: FUNC * @tc.level Level 1 - * @tc.require: AR000HG8M4 */ HWTEST_F(HyperAioTest, HyperAio_StartReadReqs_0001, testing::ext::TestSize.Level1) { GTEST_LOG_(INFO) << "HyperAioTest-begin HyperAio_StartReadReqs_0001"; std::unique_ptr hyperAio_ = std::make_unique(); - int32_t result = hyperAio_->SupportIouring(); - EXPECT_EQ((result & IOURING_APP_PERMISSION) == 0, true); - if ((result & IOURING_APP_PERMISSION) == 0) { - return; - } - result = hyperAio_->CtxInit(&callBack); + int32_t result = hyperAio_->CtxInit(&callBack); EXPECT_EQ(result, 0); + hyperAio_->initialized_.store(false); ReadInfo readInfo = {0, len, 0, nullptr, userData}; ReadReqs readReqs = {1, &readInfo}; result = hyperAio_->StartReadReqs(&readReqs); - EXPECT_EQ(result, 0); + EXPECT_EQ(result, -EPERM); + hyperAio_->initialized_.store(true); result = hyperAio_->DestroyCtx(); EXPECT_EQ(result, 0); GTEST_LOG_(INFO) << "HyperAioTest-end HyperAio_StartReadReqs_0001"; @@ -167,43 +340,114 @@ namespace { * @tc.size: MEDIUM * @tc.type: FUNC * @tc.level Level 1 - * @tc.require: AR000HG8M4 */ - HWTEST_F(HyperAioTest, HyperAio_StartReadReqs_0002, testing::ext::TestSize.Level1) + HWTEST_F(HyperAioTest, HyperAio_StartReadReqs_0002, testing::ext::TestSize.Level0) { GTEST_LOG_(INFO) << "HyperAioTest-begin HyperAio_StartReadReqs_0002"; std::unique_ptr hyperAio_ = std::make_unique(); - int32_t result = hyperAio_->SupportIouring(); - EXPECT_EQ((result & IOURING_APP_PERMISSION) == 0, true); - if ((result & IOURING_APP_PERMISSION) == 0) { - return; - } + int32_t result = hyperAio_->CtxInit(&callBack); ReadInfo readInfo = {0, len, 0, nullptr, userData}; ReadReqs readReqs = {1, &readInfo}; result = hyperAio_->StartReadReqs(&readReqs); - EXPECT_EQ(result, -EPERM); + EXPECT_EQ(result, 0); + result = hyperAio_->DestroyCtx(); + EXPECT_EQ(result, 0); GTEST_LOG_(INFO) << "HyperAioTest-end HyperAio_StartReadReqs_0002"; } + /** + * @tc.name: HyperAio_StartReadReqs_0003 + * @tc.desc: Test function of StartReadReqs() interface for SUCCESS. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ + HWTEST_F(HyperAioTest, HyperAio_StartReadReqs_0003, testing::ext::TestSize.Level1) + { + GTEST_LOG_(INFO) << "HyperAioTest-begin HyperAio_StartReadReqs_0003"; + std::unique_ptr hyperAio_ = std::make_unique(); + int32_t result = hyperAio_->CtxInit(&callBack); + EXPECT_EQ(result, 0); + auto readInfos = std::make_unique(batchSize); + for (int i = 0; i < batchSize; ++i) { + readInfos[i].fd = 0; + readInfos[i].len = len; + readInfos[i].offset = 0; + readInfos[i].buf = nullptr; + readInfos[i].userData = userData + i; + } + ReadReqs readReqs = {batchSize, readInfos.get()}; + result = hyperAio_->StartReadReqs(&readReqs); + EXPECT_EQ(result, 0); + sqe_flag = false; + result = hyperAio_->StartReadReqs(&readReqs); + EXPECT_EQ(result, -ENOMEM); + sqe_flag = true; + result = hyperAio_->DestroyCtx(); + EXPECT_EQ(result, 0); + GTEST_LOG_(INFO) << "HyperAioTest-end HyperAio_StartReadReqs_0003"; + } + + /** + * @tc.name: HyperAio_StartReadReqs_0004 + * @tc.desc: Test function of StartReadReqs() interface for SUCCESS. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ + HWTEST_F(HyperAioTest, HyperAio_StartReadReqs_0004, testing::ext::TestSize.Level1) + { + GTEST_LOG_(INFO) << "HyperAioTest-begin HyperAio_StartReadReqs_0004"; + std::unique_ptr hyperAio_ = std::make_unique(); + int32_t result = hyperAio_->CtxInit(&callBack); + EXPECT_EQ(result, 0); + auto readInfos = std::make_unique(Threshold); + for (int i = 0; i < Threshold; ++i) { + readInfos[i].fd = 0; + readInfos[i].len = len; + readInfos[i].offset = 0; + readInfos[i].buf = nullptr; + readInfos[i].userData = userData + i; + } + ReadReqs readReqs = {Threshold, readInfos.get()}; + result = hyperAio_->StartReadReqs(&readReqs); + EXPECT_EQ(result, -EINVAL); + result = hyperAio_->DestroyCtx(); + EXPECT_EQ(result, 0); + GTEST_LOG_(INFO) << "HyperAioTest-end HyperAio_StartReadReqs_0004"; + } + + /** + * @tc.name: HyperAio_StartReadReqs_0005 + * @tc.desc: Test function of StartReadReqs() interface for SUCCESS. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ + HWTEST_F(HyperAioTest, HyperAio_StartReadReqs_0005, testing::ext::TestSize.Level1) + { + GTEST_LOG_(INFO) << "HyperAioTest-begin HyperAio_StartReadReqs_0005"; + std::unique_ptr hyperAio_ = std::make_unique(); + int32_t result = hyperAio_->StartReadReqs(nullptr); + EXPECT_EQ(result, -EINVAL); + GTEST_LOG_(INFO) << "HyperAioTest-end HyperAio_StartReadReqs_0005"; + } + /** * @tc.name: HyperAio_StartCancelReqs_0000 * @tc.desc: Test function of StartCancelReqs() interface for SUCCESS. * @tc.size: MEDIUM * @tc.type: FUNC * @tc.level Level 1 - * @tc.require: AR000HG8M4 */ HWTEST_F(HyperAioTest, HyperAio_StartCancelReqs_0000, testing::ext::TestSize.Level1) { GTEST_LOG_(INFO) << "HyperAioTest-begin HyperAio_StartCancelReqs_0000"; std::unique_ptr hyperAio_ = std::make_unique(); - int32_t result = hyperAio_->SupportIouring(); - EXPECT_EQ((result & IOURING_APP_PERMISSION) == 0, true); - if ((result & IOURING_APP_PERMISSION) == 0) { - return; - } - result = hyperAio_->CtxInit(nullptr); - EXPECT_EQ(result, -EINVAL); + int32_t result = hyperAio_->CtxInit(&callBack); + result = hyperAio_->StartCancelReqs(nullptr); + result = hyperAio_->DestroyCtx(); + EXPECT_EQ(result, 0); GTEST_LOG_(INFO) << "HyperAioTest-end HyperAio_StartCancelReqs_0000"; } @@ -213,23 +457,18 @@ namespace { * @tc.size: MEDIUM * @tc.type: FUNC * @tc.level Level 1 - * @tc.require: AR000HG8M4 */ HWTEST_F(HyperAioTest, HyperAio_StartCancelReqs_0001, testing::ext::TestSize.Level1) { GTEST_LOG_(INFO) << "HyperAioTest-begin HyperAio_StartCancelReqs_0001"; std::unique_ptr hyperAio_ = std::make_unique(); - int32_t result = hyperAio_->SupportIouring(); - EXPECT_EQ((result & IOURING_APP_PERMISSION) == 0, true); - if ((result & IOURING_APP_PERMISSION) == 0) { - return; - } - result = hyperAio_->CtxInit(&callBack); - EXPECT_EQ(result, 0); + int32_t result = hyperAio_->CtxInit(&callBack); + hyperAio_->initialized_.store(false); CancelInfo cancelInfo = {userData, 0}; CancelReqs cancelReqs = {1, &cancelInfo}; result = hyperAio_->StartCancelReqs(&cancelReqs); - EXPECT_EQ(result, 0); + EXPECT_EQ(result, -EPERM); + hyperAio_->initialized_.store(true); result = hyperAio_->DestroyCtx(); EXPECT_EQ(result, 0); GTEST_LOG_(INFO) << "HyperAioTest-end HyperAio_StartCancelReqs_0001"; @@ -241,22 +480,147 @@ namespace { * @tc.size: MEDIUM * @tc.type: FUNC * @tc.level Level 1 - * @tc.require: AR000HG8M4 */ - HWTEST_F(HyperAioTest, HyperAio_StartCancelReqs_0002, testing::ext::TestSize.Level1) + HWTEST_F(HyperAioTest, HyperAio_StartCancelReqs_0002, testing::ext::TestSize.Level0) { GTEST_LOG_(INFO) << "HyperAioTest-begin HyperAio_StartCancelReqs_0002"; std::unique_ptr hyperAio_ = std::make_unique(); - int32_t result = hyperAio_->SupportIouring(); - EXPECT_EQ((result & IOURING_APP_PERMISSION) == 0, true); - if ((result & IOURING_APP_PERMISSION) == 0) { - return; - } + int32_t result = hyperAio_->CtxInit(&callBack); CancelInfo cancelInfo = {userData, 0}; CancelReqs cancelReqs = {1, &cancelInfo}; result = hyperAio_->StartCancelReqs(&cancelReqs); - EXPECT_EQ(result, -EPERM); + EXPECT_EQ(result, 0); + result = hyperAio_->DestroyCtx(); + EXPECT_EQ(result, 0); GTEST_LOG_(INFO) << "HyperAioTest-end HyperAio_StartCancelReqs_0002"; } + + /** + * @tc.name: HyperAio_StartCancelReqs_0003 + * @tc.desc: Test function of StartCancelReqs() interface for SUCCESS. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ + HWTEST_F(HyperAioTest, HyperAio_StartCancelReqs_0003, testing::ext::TestSize.Level1) + { + GTEST_LOG_(INFO) << "HyperAioTest-begin HyperAio_StartCancelReqs_0003"; + std::unique_ptr hyperAio_ = std::make_unique(); + int32_t result = hyperAio_->CtxInit(&callBack); + EXPECT_EQ(result, 0); + auto cancelInfos = std::make_unique(batchSize); + for (int i = 0; i < batchSize; ++i) { + cancelInfos[i].userData = userData + i; + cancelInfos[i].targetUserData = userData + i; + } + CancelReqs cancelReqs = {batchSize, cancelInfos.get()}; + result = hyperAio_->StartCancelReqs(&cancelReqs); + EXPECT_EQ(result, 0); + sqe_flag = false; + result = hyperAio_->StartCancelReqs(&cancelReqs); + EXPECT_EQ(result, -ENOMEM); + sqe_flag = true; + result = hyperAio_->DestroyCtx(); + EXPECT_EQ(result, 0); + GTEST_LOG_(INFO) << "HyperAioTest-end HyperAio_StartCancelReqs_0003"; + } + + /** + * @tc.name: HyperAio_StartCancelReqs_0004 + * @tc.desc: Test function of StartCancelReqs() interface for SUCCESS. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ + HWTEST_F(HyperAioTest, HyperAio_StartCancelReqs_0004, testing::ext::TestSize.Level1) + { + GTEST_LOG_(INFO) << "HyperAioTest-begin HyperAio_StartCancelReqs_0004"; + std::unique_ptr hyperAio_ = std::make_unique(); + int32_t result = hyperAio_->CtxInit(&callBack); + EXPECT_EQ(result, 0); + auto cancelInfos = std::make_unique(Threshold); + for (int i = 0; i < Threshold; ++i) { + cancelInfos[i].userData = userData + i; + cancelInfos[i].targetUserData = userData + i; + } + CancelReqs cancelReqs = {Threshold, cancelInfos.get()}; + result = hyperAio_->StartCancelReqs(&cancelReqs); + EXPECT_EQ(result, -EINVAL); + result = hyperAio_->DestroyCtx(); + EXPECT_EQ(result, 0); + GTEST_LOG_(INFO) << "HyperAioTest-end HyperAio_StartCancelReqs_0004"; + } + + /** + * @tc.name: HyperAio_StartCancelReqs_0005 + * @tc.desc: Test function of StartCancelReqs() interface for SUCCESS. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ + HWTEST_F(HyperAioTest, HyperAio_StartCancelReqs_0005, testing::ext::TestSize.Level1) + { + GTEST_LOG_(INFO) << "HyperAioTest-begin HyperAio_StartCancelReqs_0005"; + std::unique_ptr hyperAio_ = std::make_unique(); + int32_t result = hyperAio_->StartCancelReqs(nullptr); + EXPECT_EQ(result, -EINVAL); + GTEST_LOG_(INFO) << "HyperAioTest-end HyperAio_StartCancelReqs_0005"; + } + + /** + * @tc.name: HyperAio_HarvestRes_0000 + * @tc.desc: Test function of HarvestRes() interface for SUCCESS. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ + HWTEST_F(HyperAioTest, HyperAio_HarvestRes_0000, testing::ext::TestSize.Level1) + { + GTEST_LOG_(INFO) << "HyperAioTest-begin HyperAio_HarvestRes_0000"; + std::unique_ptr hyperAio_ = std::make_unique(); + int32_t result = hyperAio_->CtxInit(&callBack); + EXPECT_EQ(result, 0); + wait_flag = false; + hyperAio_->pImpl_ = nullptr; + result = hyperAio_->DestroyCtx(); + EXPECT_EQ(result, 0); + GTEST_LOG_(INFO) << "HyperAioTest-end HyperAio_HarvestRes_0000"; + } + + /** + * @tc.name: HyperAio_HarvestRes_0001 + * @tc.desc: Test function of HarvestRes() interface for SUCCESS. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ + HWTEST_F(HyperAioTest, HyperAio_HarvestRes_0001, testing::ext::TestSize.Level1) + { + GTEST_LOG_(INFO) << "HyperAioTest-begin HyperAio_HarvestRes_0001"; + std::unique_ptr hyperAio_ = std::make_unique(); + int32_t result = hyperAio_->CtxInit(&callBack); + EXPECT_EQ(result, 0); + cqe_res_flag = false; + std::this_thread::sleep_for(std::chrono::seconds(2)); + result = hyperAio_->DestroyCtx(); + EXPECT_EQ(result, 0); + GTEST_LOG_(INFO) << "HyperAioTest-end HyperAio_HarvestRes_0001"; + } + + /** + * @tc.name: HyperAio_DestroyCtx_0000 + * @tc.desc: Test function of DestroyCtx() interface for SUCCESS. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ + HWTEST_F(HyperAioTest, HyperAio_DestroyCtx_0000, testing::ext::TestSize.Level1) + { + GTEST_LOG_(INFO) << "HyperAioTest-begin HyperAio_DestroyCtx_0000"; + std::unique_ptr hyperAio_ = std::make_unique(); + int32_t result = hyperAio_->DestroyCtx(); + EXPECT_EQ(result, 0); + GTEST_LOG_(INFO) << "HyperAioTest-end HyperAio_DestroyCtx_0000"; + } #endif } diff --git a/interfaces/test/unittest/hyperaio/include/liburing.h b/interfaces/test/unittest/hyperaio/include/liburing.h new file mode 100644 index 0000000000000000000000000000000000000000..b00112be3c3b823357047843934b4b6ad5451c7e --- /dev/null +++ b/interfaces/test/unittest/hyperaio/include/liburing.h @@ -0,0 +1,126 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef UNITTEST_HYPERAIO_INCLUDE_LIBURING_H +#define UNITTEST_HYPERAIO_INCLUDE_LIBURING_H + +#include +#include +namespace OHOS { +namespace HyperAio { +#define O_RDWR 02 +inline bool sqe_flag = true; +inline bool init_flag = true; +inline bool wait_flag = true; +inline bool cqe_res_flag = true; +struct io_uring_sqe { + int32_t data; +}; + +struct io_uring_cqe { + int32_t data; + uint64_t user_data; + int32_t res; + uint32_t flags; +}; + +struct io_uring { + std::vector> sqe_list; + io_uring() {} + ~io_uring() {} + inline io_uring_sqe *io_uring_get_sqe() + { + auto sqe = std::make_unique(); + io_uring_sqe *raw_sqe = sqe.get(); + sqe_list.push_back(std::move(sqe)); + return raw_sqe; + } + void clear_sqes() + { + sqe_list.clear(); + } +}; + +inline struct io_uring_sqe *io_uring_get_sqe(struct io_uring *ring) +{ + if (sqe_flag) { + return ring->io_uring_get_sqe(); + } + return nullptr; +} + +inline int io_uring_submit(struct io_uring *ring) +{ + return 1; +} + +inline int io_uring_queue_init(unsigned entries, struct io_uring *ring, unsigned flags) +{ + if (init_flag) { + return 1; + } + return -1; +} + +inline void io_uring_sqe_set_data(struct io_uring_sqe *sqe, void *data) +{ + return; +} + +inline void io_uring_prep_openat(struct io_uring_sqe *sqe, int dfd, + const char *path, int flags, mode_t mode) +{ + return; +} + +inline void io_uring_prep_read(struct io_uring_sqe *sqe, int fd, + void *buf, unsigned nbytes, uint64_t offset) +{ + return; +} + +inline void io_uring_prep_cancel(struct io_uring_sqe *sqe, + void *user_data, int flags) +{ + return; +} + +inline int io_uring_wait_cqe(struct io_uring *ring, struct io_uring_cqe **cqe_ptr) +{ + std::this_thread::sleep_for(std::chrono::seconds(1)); + if (!wait_flag) { + wait_flag = true; + return -1; + } + *cqe_ptr = new io_uring_cqe(); + (*cqe_ptr)->res = cqe_res_flag ? 0 : -1; + cqe_res_flag = true; + return 1; +} + +inline void io_uring_cqe_seen(struct io_uring *ring, struct io_uring_cqe *cqe) +{ + delete cqe; + return; +} + +inline void io_uring_queue_exit(struct io_uring *ring) +{ + return; +} + +} +} +#endif \ No newline at end of file diff --git a/interfaces/test/unittest/js/BUILD.gn b/interfaces/test/unittest/js/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..31b84da705a2c4753b92d8cf0e770cf9e761bd52 --- /dev/null +++ b/interfaces/test/unittest/js/BUILD.gn @@ -0,0 +1,194 @@ +# Copyright (C) 2025 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/test.gni") +import("//foundation/filemanagement/file_api/file_api.gni") + +ohos_unittest("ani_file_fs_mock_test") { + branch_protector_ret = "pac_ret" + testonly = true + + module_out_path = "file_api/file_api" + + include_dirs = [ + "${file_api_path}/interfaces/kits/js/src/mod_fs/class_file", + "${file_api_path}/interfaces/kits/js/src/mod_fs/class_stat", + "${file_api_path}/interfaces/kits/js/src/mod_fs/properties", + "${file_api_path}/interfaces/test/unittest/js/mod_fs/properties/mock", + ] + + sources = [ + "mod_fs/class_file/fs_file_mock_test.cpp", + "mod_fs/class_stat/fs_stat_mock_test.cpp", + "mod_fs/properties/access_core_mock_test.cpp", + "mod_fs/properties/copy_file_core_mock_test.cpp", + "mod_fs/properties/mkdir_core_mock_test.cpp", + "mod_fs/properties/move_core_mock_test.cpp", + "mod_fs/properties/mock/system_mock.cpp", + "mod_fs/properties/mock/uv_fs_mock.cpp", + "mod_fs/properties/open_core_mock_test.cpp", + "mod_fs/properties/read_core_mock_test.cpp", + "mod_fs/properties/stat_core_mock_test.cpp", + "mod_fs/properties/truncate_core_mock_test.cpp", + "mod_fs/properties/unlink_core_mock_test.cpp", + "mod_fs/properties/write_core_mock_test.cpp", + ] + + deps = [ + "${file_api_path}/interfaces/kits/native:remote_uri_native", + "${file_api_path}/interfaces/kits/native:task_signal_native", + "${file_api_path}/interfaces/kits/rust:rust_file", + "${utils_path}/filemgmt_libfs:filemgmt_libfs", + "${utils_path}/filemgmt_libhilog:filemgmt_libhilog", + "${file_api_path}/interfaces/kits/js:ani_file_fs", + ] + + external_deps = [ + "ability_runtime:ability_manager", + "app_file_service:fileuri_native", + "c_utils:utils", + "googletest:gmock_main", + "googletest:gtest_main", + "hilog:libhilog", + "ipc:ipc_core", + "libuv:uv", + ] + + defines = [ + "private=public", + ] + + use_exceptions = true +} + +ohos_unittest("ani_file_fs_test") { + branch_protector_ret = "pac_ret" + testonly = true + + module_out_path = "file_api/file_api" + + resource_config_file = "../resource/ohos_test.xml" + + include_dirs = [ + "${file_api_path}/interfaces/kits/js/src/mod_fs/class_atomicfile", + "${file_api_path}/interfaces/kits/js/src/mod_fs/class_file", + "${file_api_path}/interfaces/kits/js/src/mod_fs/class_randomaccessfile", + "${file_api_path}/interfaces/kits/js/src/mod_fs/class_readeriterator", + "${file_api_path}/interfaces/kits/js/src/mod_fs/class_stat", + "${file_api_path}/interfaces/kits/js/src/mod_fs/class_stream", + "${file_api_path}/interfaces/kits/js/src/mod_fs/class_tasksignal", + "${file_api_path}/interfaces/kits/js/src/mod_fs/properties", + ] + + sources = [ + "mod_fs/class_file/fs_file_test.cpp", + "mod_fs/class_stat/fs_stat_test.cpp", + "mod_fs/properties/access_core_test.cpp", + "mod_fs/properties/close_core_test.cpp", + "mod_fs/properties/copy_file_core_test.cpp", + "mod_fs/properties/listfile_core_test.cpp", + "mod_fs/properties/move_core_test.cpp", + "mod_fs/properties/open_core_test.cpp", + "mod_fs/properties/read_core_test.cpp", + "mod_fs/properties/read_text_core_test.cpp", + "mod_fs/properties/rmdir_core_test.cpp", + "mod_fs/properties/stat_core_test.cpp", + "mod_fs/properties/truncate_core_test.cpp", + "mod_fs/properties/write_core_test.cpp", + ] + + deps = [ + "${file_api_path}/interfaces/kits/native:remote_uri_native", + "${file_api_path}/interfaces/kits/native:task_signal_native", + "${file_api_path}/interfaces/kits/rust:rust_file", + "${utils_path}/filemgmt_libfs:filemgmt_libfs", + "${utils_path}/filemgmt_libhilog:filemgmt_libhilog", + "${file_api_path}/interfaces/kits/js:ani_file_fs", + ] + + external_deps = [ + "ability_runtime:ability_manager", + "app_file_service:fileuri_native", + "c_utils:utils", + "googletest:gtest_main", + "hilog:libhilog", + "ipc:ipc_core", + "libuv:uv", + ] + + defines = [ + "private=public", + ] + + use_exceptions = true +} + +ohos_unittest("ani_file_hash_test") { + module_out_path = "file_api/file_api" + + resource_config_file = "../resource/ohos_test.xml" + + sources = [ + "mod_hash/hash_core_test.cpp", + ] + + include_dirs = [ + "mock/libuv", + "${file_api_path}/interfaces/kits/js/src/mod_hash", + ] + + deps = [ + "${utils_path}/filemgmt_libhilog:filemgmt_libhilog", + "${utils_path}/filemgmt_libfs:filemgmt_libfs", + "${file_api_path}/interfaces/kits/js:ani_file_hash", + ] + + external_deps = [ + "c_utils:utils", + "hilog:libhilog", + "libuv:uv", + "googletest:gmock_main", + "googletest:gtest_main", + ] + + use_exceptions = true +} + +ohos_unittest("ani_file_securitylabel_test") { + module_out_path = "file_api/file_api" + + resource_config_file = "../resource/ohos_test.xml" + + sources = [ + "mod_securitylabel/securitylabel_core_test.cpp", + ] + + include_dirs = [ + "${file_api_path}/interfaces/kits/js/src/mod_securitylabel", + ] + + deps = [ + "${utils_path}/filemgmt_libhilog:filemgmt_libhilog", + "${utils_path}/filemgmt_libfs:filemgmt_libfs", + "${file_api_path}/interfaces/kits/js:ani_file_securitylabel", + ] + + external_deps = [ + "c_utils:utils", + "hilog:libhilog", + "googletest:gmock_main", + "googletest:gtest_main", + ] + + use_exceptions = true +} \ No newline at end of file diff --git a/interfaces/test/unittest/js/mod_fs/class_file/fs_file_mock_test.cpp b/interfaces/test/unittest/js/mod_fs/class_file/fs_file_mock_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..0dcd0e963a7f43f21e8164972a3e0ec674dfc5c4 --- /dev/null +++ b/interfaces/test/unittest/js/mod_fs/class_file/fs_file_mock_test.cpp @@ -0,0 +1,386 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "file_entity.h" +#include "fs_file.h" +#include "system_mock.h" +#include "uv_fs_mock.h" + +#include +#include + +namespace OHOS::FileManagement::ModuleFileIO::Test { +using namespace testing; +using namespace testing::ext; +using namespace std; + +class FsFileMockTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); + static inline shared_ptr uvMock = nullptr; + static inline shared_ptr sys = nullptr; + std::unique_ptr fileEntity; + std::unique_ptr fsFile; +}; + +void FsFileMockTest::SetUpTestCase(void) +{ + GTEST_LOG_(INFO) << "SetUpTestCase"; + uvMock = std::make_shared(); + Uvfs::ins = uvMock; + sys = std::make_shared(); + System::ins = sys; +} + +void FsFileMockTest::TearDownTestCase(void) +{ + GTEST_LOG_(INFO) << "TearDownTestCase"; + Uvfs::ins = nullptr; + uvMock = nullptr; + System::ins = nullptr; + sys = nullptr; +} + +void FsFileMockTest::SetUp(void) +{ + GTEST_LOG_(INFO) << "SetUp"; + + fileEntity = std::make_unique(); + const int fdValue = 3; + const bool isClosed = false; + fileEntity->fd_ = std::make_unique(fdValue, isClosed); + fileEntity->path_ = "/data/test/file_test.txt"; + fileEntity->uri_ = ""; + fsFile = std::make_unique(std::move(fileEntity)); +} + +void FsFileMockTest::TearDown(void) +{ + GTEST_LOG_(INFO) << "TearDown"; +} + +/** +* @tc.name: FsFileMockTest_GetPath_001 +* @tc.desc: Test function of GetPath() interface for SUCCESS. +* @tc.size: MEDIUM +* @tc.type: FUNC +* @tc.level Level 1 +*/ +HWTEST_F(FsFileMockTest, FsFileMockTest_GetPath_001, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "FsFileMockTest-begin FsFileMockTest_GetPath_001"; + + uv_fs_t mock_req; + mock_req.ptr = const_cast("/data/test/file_test.txt"); + + EXPECT_CALL(*uvMock, uv_fs_realpath(_, _, _, _)) + .WillOnce(Invoke([&](uv_loop_t*, uv_fs_t* req, const char*, uv_fs_cb) { + *req = mock_req; + return 0; + })); + auto result = fsFile->GetPath(); + EXPECT_EQ(result.IsSuccess(), true); + + GTEST_LOG_(INFO) << "FsFileMockTest-end FsFileMockTest_GetPath_001"; +} + +/** +* @tc.name: FsFileMockTest_GetPath_002 +* @tc.desc: Test function of GetPath() interface for ERROR. +* @tc.size: MEDIUM +* @tc.type: FUNC +* @tc.level Level 1 +*/ +HWTEST_F(FsFileMockTest, FsFileMockTest_GetPath_002, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "FsFileMockTest-begin FsFileMockTest_GetPath_002"; + + fsFile->fileEntity->path_ = "/invalid/path"; + EXPECT_CALL(*uvMock, uv_fs_realpath(_, _, _, _)).WillOnce(Return(-1)); + auto result = fsFile->GetPath(); + EXPECT_EQ(result.IsSuccess(), false); + + GTEST_LOG_(INFO) << "FsFileMockTest-end FsFileMockTest_GetPath_002"; +} + +/** +* @tc.name: FsFileMockTest_GetName_003 +* @tc.desc: Test function of GetName() interface for ERROR. +* @tc.size: MEDIUM +* @tc.type: FUNC +* @tc.level Level 1 +*/ +HWTEST_F(FsFileMockTest, FsFileMockTest_GetName_003, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "FsFileMockTest-begin FsFileMockTest_GetName_003"; + + fsFile->fileEntity->path_ = "/invalid/path"; + EXPECT_CALL(*uvMock, uv_fs_realpath(_, _, _, _)).WillOnce(Return(-1)); + auto result = fsFile->GetName(); + EXPECT_EQ(result.IsSuccess(), false); + + GTEST_LOG_(INFO) << "FsFileMockTest-end FsFileMockTest_GetName_003"; +} + +/** +* @tc.name: FsFileMockTest_GetName_004 +* @tc.desc: Test function of GetName() interface for ERROR. +* @tc.size: MEDIUM +* @tc.type: FUNC +* @tc.level Level 1 +*/ +HWTEST_F(FsFileMockTest, FsFileMockTest_GetName_004, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "FsFileMockTest-begin FsFileMockTest_GetName_004"; + + fsFile->fileEntity->path_ = "file_test.txt"; + EXPECT_CALL(*uvMock, uv_fs_realpath(_, _, _, _)).WillOnce(Return(-1)); + auto result = fsFile->GetName(); + EXPECT_EQ(result.IsSuccess(), false); + + GTEST_LOG_(INFO) << "FsFileMockTest-end FsFileMockTest_GetName_004"; +} + +/** +* @tc.name: FsFileMockTest_GetParent_005 +* @tc.desc: Test function of GetParent() interface for ERROR. +* @tc.size: MEDIUM +* @tc.type: FUNC +* @tc.level Level 1 +*/ +HWTEST_F(FsFileMockTest, FsFileMockTest_GetParent_005, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "FsFileMockTest-begin FsFileMockTest_GetParent_005"; + + fsFile->fileEntity->path_ = "/invalid/path"; + EXPECT_CALL(*uvMock, uv_fs_realpath(_, _, _, _)).WillOnce(Return(-1)); + auto result = fsFile->GetParent(); + EXPECT_EQ(result.IsSuccess(), false); + + GTEST_LOG_(INFO) << "FsFileMockTest-end FsFileMockTest_GetParent_005"; +} + +/** +* @tc.name: FsFileMockTest_GetName_006 +* @tc.desc: Test function of GetName() interface for SUCCESS. +* @tc.size: MEDIUM +* @tc.type: FUNC +* @tc.level Level 1 +*/ +HWTEST_F(FsFileMockTest, FsFileMockTest_GetName_006, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "FsFileMockTest-begin FsFileMockTest_GetName_006"; + + uv_fs_t mock_req; + mock_req.ptr = const_cast("/file_test.txt"); + + EXPECT_CALL(*uvMock, uv_fs_realpath(_, _, _, _)) + .WillOnce(Invoke([&](uv_loop_t*, uv_fs_t* req, const char*, uv_fs_cb) { + *req = mock_req; + return 0; + })); + auto result = fsFile->GetName(); + EXPECT_EQ(result.IsSuccess(), true); + + GTEST_LOG_(INFO) << "FsFileMockTest-end FsFileMockTest_GetName_006"; +} + +/** +* @tc.name: FsFileMockTest_GetParent_007 +* @tc.desc: Test function of GetParent() interface for SUCCESS. +* @tc.size: MEDIUM +* @tc.type: FUNC +* @tc.level Level 1 +*/ +HWTEST_F(FsFileMockTest, FsFileMockTest_GetParent_007, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "FsFileMockTest-begin FsFileMockTest_GetParent_007"; + + uv_fs_t mock_req; + mock_req.ptr = const_cast("/test/dir_test"); + + EXPECT_CALL(*uvMock, uv_fs_realpath(_, _, _, _)) + .WillOnce(Invoke([&](uv_loop_t*, uv_fs_t* req, const char*, uv_fs_cb) { + *req = mock_req; + return 0; + })); + auto result = fsFile->GetParent(); + EXPECT_EQ(result.IsSuccess(), true); + + GTEST_LOG_(INFO) << "FsFileMockTest-end FsFileMockTest_GetParent_007"; +} + +/** +* @tc.name: FsFileMockTest_GetName_008 +* @tc.desc: Test function of GetName() interface for FALSE. +* @tc.size: MEDIUM +* @tc.type: FUNC +* @tc.level Level 1 +*/ +HWTEST_F(FsFileMockTest, FsFileMockTest_GetName_008, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "FsFileMockTest-begin FsFileMockTest_GetName_008"; + + uv_fs_t mock_req; + mock_req.ptr = const_cast("file_test.txt"); + + EXPECT_CALL(*uvMock, uv_fs_realpath(_, _, _, _)) + .WillOnce(Invoke([&](uv_loop_t*, uv_fs_t* req, const char*, uv_fs_cb) { + *req = mock_req; + return 0; + })); + auto result = fsFile->GetName(); + EXPECT_EQ(result.IsSuccess(), false); + + GTEST_LOG_(INFO) << "FsFileMockTest-end FsFileMockTest_GetName_008"; +} + +/** +* @tc.name: FsFileMockTest_GetParent_009 +* @tc.desc: Test function of GetParent() interface for FALSE. +* @tc.size: MEDIUM +* @tc.type: FUNC +* @tc.level Level 1 +*/ +HWTEST_F(FsFileMockTest, FsFileMockTest_GetParent_009, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "FsFileMockTest-begin FsFileMockTest_GetParent_009"; + + uv_fs_t mock_req; + mock_req.ptr = const_cast("dir_test"); + + EXPECT_CALL(*uvMock, uv_fs_realpath(_, _, _, _)) + .WillOnce(Invoke([&](uv_loop_t*, uv_fs_t* req, const char*, uv_fs_cb) { + *req = mock_req; + return 0; + })); + auto result = fsFile->GetParent(); + EXPECT_EQ(result.IsSuccess(), false); + + GTEST_LOG_(INFO) << "FsFileMockTest-end FsFileMockTest_GetParent_009"; +} + +/** +* @tc.name: FsFileMockTest_Lock_010 +* @tc.desc: Test function of Lock() interface for SUCCESS. +* @tc.size: MEDIUM +* @tc.type: FUNC +* @tc.level Level 1 +*/ +HWTEST_F(FsFileMockTest, FsFileMockTest_Lock_010, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "FsFileMockTest-begin FsFileMockTest_Lock_010"; + + EXPECT_CALL(*sys, flock(_, _)).WillOnce(Return(1)); + auto result = fsFile->Lock(true); + EXPECT_EQ(result.IsSuccess(), true); + + GTEST_LOG_(INFO) << "FsFileMockTest-end FsFileMockTest_Lock_010"; +} + +/** +* @tc.name: FsFileMockTest_Lock_011 +* @tc.desc: Test function of Lock() interface for FALSE. +* @tc.size: MEDIUM +* @tc.type: FUNC +* @tc.level Level 1 +*/ +HWTEST_F(FsFileMockTest, FsFileMockTest_Lock_011, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "FsFileMockTest-begin FsFileMockTest_Lock_011"; + + EXPECT_CALL(*sys, flock(_, _)).WillOnce(Return(-1)); + auto result = fsFile->Lock(false); + EXPECT_EQ(result.IsSuccess(), false); + + GTEST_LOG_(INFO) << "FsFileMockTest-end FsFileMockTest_Lock_011"; +} + +/** +* @tc.name: FsFileMockTest_TryLock_012 +* @tc.desc: Test function of TryLock() interface for SUCCESS. +* @tc.size: MEDIUM +* @tc.type: FUNC +* @tc.level Level 1 +*/ +HWTEST_F(FsFileMockTest, FsFileMockTest_TryLock_012, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "FsFileMockTest-begin FsFileMockTest_TryLock_012"; + + EXPECT_CALL(*sys, flock(_, _)).WillOnce(Return(1)); + auto result = fsFile->TryLock(true); + EXPECT_EQ(result.IsSuccess(), true); + + GTEST_LOG_(INFO) << "FsFileMockTest-end FsFileMockTest_TryLock_012"; +} + +/** +* @tc.name: FsFileMockTest_TryLock_013 +* @tc.desc: Test function of TryLock() interface for FALSE. +* @tc.size: MEDIUM +* @tc.type: FUNC +* @tc.level Level 1 +*/ +HWTEST_F(FsFileMockTest, FsFileMockTest_TryLock_013, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "FsFileMockTest-begin FsFileMockTest_TryLock_013"; + + EXPECT_CALL(*sys, flock(_, _)).WillOnce(Return(-1)); + auto result = fsFile->TryLock(false); + EXPECT_EQ(result.IsSuccess(), false); + + GTEST_LOG_(INFO) << "FsFileMockTest-end FsFileMockTest_TryLock_013"; +} + +/** +* @tc.name: FsFileMockTest_UnLock_014 +* @tc.desc: Test function of UnLock() interface for SUCCESS. +* @tc.size: MEDIUM +* @tc.type: FUNC +* @tc.level Level 1 +*/ +HWTEST_F(FsFileMockTest, FsFileMockTest_UnLock_014, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "FsFileMockTest-begin FsFileMockTest_UnLock_014"; + + EXPECT_CALL(*sys, flock(_, _)).WillOnce(Return(1)); + auto result = fsFile->UnLock(); + EXPECT_EQ(result.IsSuccess(), true); + + GTEST_LOG_(INFO) << "FsFileMockTest-end FsFileMockTest_UnLock_014"; +} + +/** +* @tc.name: FsFileMockTest_UnLock_015 +* @tc.desc: Test function of UnLock() interface for FALSE. +* @tc.size: MEDIUM +* @tc.type: FUNC +* @tc.level Level 1 +*/ +HWTEST_F(FsFileMockTest, FsFileMockTest_UnLock_015, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "FsFileMockTest-begin FsFileMockTest_UnLock_015"; + + EXPECT_CALL(*sys, flock(_, _)).WillOnce(Return(-1)); + auto result = fsFile->UnLock(); + EXPECT_EQ(result.IsSuccess(), false); + + GTEST_LOG_(INFO) << "FsFileMockTest-end FsFileMockTest_UnLock_015"; +} + +} \ No newline at end of file diff --git a/interfaces/test/unittest/js/mod_fs/class_file/fs_file_test.cpp b/interfaces/test/unittest/js/mod_fs/class_file/fs_file_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..242d472ffe6fed6841812d3792601e06fc528194 --- /dev/null +++ b/interfaces/test/unittest/js/mod_fs/class_file/fs_file_test.cpp @@ -0,0 +1,278 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "file_entity.h" +#include "fs_file.h" + +#include + +namespace OHOS::FileManagement::ModuleFileIO::Test { +using namespace testing; +using namespace testing::ext; +using namespace std; + +class FsFileTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); + std::unique_ptr fileEntity; + std::unique_ptr fsFile; +}; + +void FsFileTest::SetUpTestCase(void) +{ + GTEST_LOG_(INFO) << "SetUpTestCase"; +} + +void FsFileTest::TearDownTestCase(void) +{ + GTEST_LOG_(INFO) << "TearDownTestCase"; +} + +void FsFileTest::SetUp(void) +{ + GTEST_LOG_(INFO) << "SetUp"; + + fileEntity = std::make_unique(); + const int fdValue = 3; + const bool isClosed = false; + fileEntity->fd_ = std::make_unique(fdValue, isClosed); + fileEntity->path_ = "/data/test/file_test.txt"; + fileEntity->uri_ = ""; + fsFile = std::make_unique(std::move(fileEntity)); +} + +void FsFileTest::TearDown(void) +{ + GTEST_LOG_(INFO) << "TearDown"; +} + +/** +* @tc.name: FsFileTest_Constructor_001 +* @tc.desc: Test function of FsFile::Constructor() interface for SUCCESS. +* @tc.size: MEDIUM +* @tc.type: FUNC +* @tc.level Level 1 +*/ +HWTEST_F(FsFileTest, FsFileTest_Constructor_001, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "FsFileTest-begin FsFileTest_Constructor_001"; + + auto result = FsFile::Constructor(); + EXPECT_EQ(result.IsSuccess(), true); + + GTEST_LOG_(INFO) << "FsFileTest-end FsFileTest_Constructor_001"; +} + +/** +* @tc.name: FsFileTest_GetFD_002 +* @tc.desc: Test function of GetFD() interface for SUCCESS. +* @tc.size: MEDIUM +* @tc.type: FUNC +* @tc.level Level 1 +*/ +HWTEST_F(FsFileTest, FsFileTest_GetFD_002, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "FsFileTest-begin FsFileTest_GetFD_002"; + + auto result = fsFile->GetFD(); + EXPECT_EQ(result.IsSuccess(), true); + + GTEST_LOG_(INFO) << "FsFileTest-end FsFileTest_GetFD_002"; +} + +/** +* @tc.name: FsFileTest_GetFD_003 +* @tc.desc: Test function of GetFD() interface for ERROR. +* @tc.size: MEDIUM +* @tc.type: FUNC +* @tc.level Level 1 +*/ +HWTEST_F(FsFileTest, FsFileTest_GetFD_003, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "FsFileTest-begin FsFileTest_GetFD_003"; + + fsFile = std::make_unique(nullptr); + auto result = fsFile->GetFD(); + EXPECT_EQ(result.IsSuccess(), false); + + GTEST_LOG_(INFO) << "FsFileTest-end FsFileTest_GetFD_003"; +} + +/** +* @tc.name: FsFileTest_GetPath_004 +* @tc.desc: Test function of GetPath() interface for ERROR. +* @tc.size: MEDIUM +* @tc.type: FUNC +* @tc.level Level 1 +*/ +HWTEST_F(FsFileTest, FsFileTest_GetPath_004, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "FsFileTest-begin FsFileTest_GetPath_004"; + + fsFile = std::make_unique(nullptr); + auto result = fsFile->GetPath(); + EXPECT_EQ(result.IsSuccess(), false); + + GTEST_LOG_(INFO) << "FsFileTest-end FsFileTest_GetPath_004"; +} + +/** +* @tc.name: FsFileTest_GetName_005 +* @tc.desc: Test function of GetName() interface for ERROR. +* @tc.size: MEDIUM +* @tc.type: FUNC +* @tc.level Level 1 +*/ +HWTEST_F(FsFileTest, FsFileTest_GetName_005, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "FsFileTest-begin FsFileTest_GetName_005"; + + fsFile = std::make_unique(nullptr); + auto result = fsFile->GetName(); + EXPECT_EQ(result.IsSuccess(), false); + + GTEST_LOG_(INFO) << "FsFileTest-end FsFileTest_GetName_005"; +} + +/** +* @tc.name: FsFileTest_GetParent_006 +* @tc.desc: Test function of GetParent() interface for ERROR. +* @tc.size: MEDIUM +* @tc.type: FUNC +* @tc.level Level 1 +*/ +HWTEST_F(FsFileTest, FsFileTest_GetParent_006, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "FsFileTest-begin FsFileTest_GetParent_006"; + + fsFile = std::make_unique(nullptr); + auto result = fsFile->GetParent(); + EXPECT_EQ(result.IsSuccess(), false); + + GTEST_LOG_(INFO) << "FsFileTest-end FsFileTest_GetParent_006"; +} + +/** +* @tc.name: FsFileTest_Lock_007 +* @tc.desc: Test function of Lock() interface for ERROR. +* @tc.size: MEDIUM +* @tc.type: FUNC +* @tc.level Level 1 +*/ +HWTEST_F(FsFileTest, FsFileTest_Lock_007, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "FsFileTest-begin FsFileTest_Lock_007"; + + fsFile = std::make_unique(nullptr); + auto result = fsFile->Lock(true); + EXPECT_EQ(result.IsSuccess(), false); + + GTEST_LOG_(INFO) << "FsFileTest-end FsFileTest_Lock_007"; +} + +/** +* @tc.name: FsFileTest_TryLock_008 +* @tc.desc: Test function of TryLock() interface for ERROR. +* @tc.size: MEDIUM +* @tc.type: FUNC +* @tc.level Level 1 +*/ +HWTEST_F(FsFileTest, FsFileTest_TryLock_008, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "FsFileTest-begin FsFileTest_TryLock_008"; + + fsFile = std::make_unique(nullptr); + auto result = fsFile->TryLock(true); + EXPECT_EQ(result.IsSuccess(), false); + + GTEST_LOG_(INFO) << "FsFileTest-end FsFileTest_TryLock_008"; +} + +/** +* @tc.name: FsFileTest_UnLock_009 +* @tc.desc: Test function of UnLock() interface for ERROR. +* @tc.size: MEDIUM +* @tc.type: FUNC +* @tc.level Level 1 +*/ +HWTEST_F(FsFileTest, FsFileTest_UnLock_009, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "FsFileTest-begin FsFileTest_UnLock_009"; + + fsFile = std::make_unique(nullptr); + auto result = fsFile->UnLock(); + EXPECT_EQ(result.IsSuccess(), false); + + GTEST_LOG_(INFO) << "FsFileTest-end FsFileTest_UnLock_009"; +} + +/** +* @tc.name: FsFileTest_GetName_010 +* @tc.desc: Test function of GetName() interface for SUCCESS. +* @tc.size: MEDIUM +* @tc.type: FUNC +* @tc.level Level 1 +*/ +HWTEST_F(FsFileTest, FsFileTest_GetName_010, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "FsFileTest-begin FsFileTest_GetName_010"; + + fsFile->fileEntity->uri_ = "file://storage/file_test.txt"; + auto result = fsFile->GetName(); + EXPECT_EQ(result.IsSuccess(), true); + + GTEST_LOG_(INFO) << "FsFileTest-end FsFileTest_GetName_010"; +} + +/** +* @tc.name: FsFileTest_GetParent_011 +* @tc.desc: Test function of GetParent() interface for SUCCESS. +* @tc.size: MEDIUM +* @tc.type: FUNC +* @tc.level Level 1 +*/ +HWTEST_F(FsFileTest, FsFileTest_GetParent_011, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "FsFileTest-begin FsFileTest_GetParent_011"; + + fsFile->fileEntity->uri_ = "file://storage/file_test.txt"; + auto result = fsFile->GetParent(); + EXPECT_EQ(result.IsSuccess(), true); + + GTEST_LOG_(INFO) << "FsFileTest-end FsFileTest_GetParent_011"; +} + +/** +* @tc.name: FsFileTest_GetPath_012 +* @tc.desc: Test function of GetPath() interface for SUCCESS. +* @tc.size: MEDIUM +* @tc.type: FUNC +* @tc.level Level 1 +*/ +HWTEST_F(FsFileTest, FsFileTest_GetPath_012, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "FsFileTest-begin FsFileTest_GetPath_012"; + + fsFile->fileEntity->uri_ = "file://storage/file_test.txt"; + auto result = fsFile->GetPath(); + EXPECT_EQ(result.IsSuccess(), true); + + GTEST_LOG_(INFO) << "FsFileTest-end FsFileTest_GetPath_012"; +} + +} \ No newline at end of file diff --git a/interfaces/test/unittest/js/mod_fs/class_stat/fs_stat_mock_test.cpp b/interfaces/test/unittest/js/mod_fs/class_stat/fs_stat_mock_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ea2e168d5195bee7530999b4e7c3c56b30cc8a98 --- /dev/null +++ b/interfaces/test/unittest/js/mod_fs/class_stat/fs_stat_mock_test.cpp @@ -0,0 +1,118 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "fs_stat.h" +#include "../properties/mock/system_mock.h" +#include "fs_stat_entity.h" +#include "securec.h" + +#include +#include + +namespace OHOS::FileManagement::ModuleFileIO::Test { +using namespace testing; +using namespace testing::ext; +using namespace std; + +class FsStatMockTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); + static inline shared_ptr sys = nullptr; +}; + +void FsStatMockTest::SetUpTestCase(void) +{ + GTEST_LOG_(INFO) << "SetUpTestCase"; + sys = std::make_shared(); + System::ins = sys; +} + +void FsStatMockTest::TearDownTestCase(void) +{ + GTEST_LOG_(INFO) << "TearDownTestCase"; + System::ins = nullptr; + sys = nullptr; +} + +void FsStatMockTest::SetUp(void) +{ + GTEST_LOG_(INFO) << "SetUp"; +} + +void FsStatMockTest::TearDown(void) +{ + GTEST_LOG_(INFO) << "TearDown"; +} + +/** + * @tc.name: FsStatMockTest_GetLocation_001 + * @tc.desc: Test function of GetLocation() interface for SUCCESS. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(FsStatMockTest, FsStatMockTest_GetLocation_001, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "FsStatMockTes-begin FsStatMockTest_GetLocation_001"; + + std::unique_ptr statEntity; + std::unique_ptr fsStat; + statEntity = std::make_unique(); + statEntity->fileInfo_ = std::make_unique(); + statEntity->fileInfo_->isPath = true; + int length = 100; + string testPath = "/test/path"; + statEntity->fileInfo_->path = std::make_unique(length); + strncpy_s(statEntity->fileInfo_->path.get(), length, testPath.c_str(), testPath.size()); + statEntity->fileInfo_->path.get()[99] = '\0'; + fsStat = std::make_unique(std::move(statEntity)); + + EXPECT_CALL(*sys, getxattr(_, _, _, _)).WillOnce(Return(1)); + EXPECT_EQ(fsStat->GetLocation(), 1); + + GTEST_LOG_(INFO) << "FsStatMockTes-end FsStatMockTest_GetLocation_001"; +} + +/** + * @tc.name: FsStatMockTest_GetLocation_002 + * @tc.desc: Test function of GetLocation() interface for SUCCESS. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(FsStatMockTest, FsStatMockTest_GetLocation_002, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "FsStatMockTes-begin FsStatMockTest_GetLocation_002"; + + std::unique_ptr statEntity; + std::unique_ptr fsStat; + statEntity = std::make_unique(); + statEntity->fileInfo_ = std::make_unique(); + statEntity->fileInfo_->isPath = false; + const int fdValue = 3; + const bool isClosed = false; + statEntity->fileInfo_->fdg = std::make_unique(fdValue, isClosed); + fsStat = std::make_unique(std::move(statEntity)); + + EXPECT_CALL(*sys, fgetxattr(_, _, _, _)).WillOnce(Return(1)); + EXPECT_EQ(fsStat->GetLocation(), 1); + + GTEST_LOG_(INFO) << "FsStatMockTes-end FsStatMockTest_GetLocation_002"; +} + +} \ No newline at end of file diff --git a/interfaces/test/unittest/js/mod_fs/class_stat/fs_stat_test.cpp b/interfaces/test/unittest/js/mod_fs/class_stat/fs_stat_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..15a8640f2751309fcf229bf2077e668dbc550b74 --- /dev/null +++ b/interfaces/test/unittest/js/mod_fs/class_stat/fs_stat_test.cpp @@ -0,0 +1,472 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "fs_stat.h" + +#include + + +namespace OHOS::FileManagement::ModuleFileIO::Test { +using namespace testing; +using namespace testing::ext; +using namespace std; + +class FsStatTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); +}; + +void FsStatTest::SetUpTestCase(void) +{ + GTEST_LOG_(INFO) << "SetUpTestCase"; +} + +void FsStatTest::TearDownTestCase(void) +{ + GTEST_LOG_(INFO) << "TearDownTestCase"; +} + +void FsStatTest::SetUp(void) +{ + GTEST_LOG_(INFO) << "SetUp"; +} + +void FsStatTest::TearDown(void) +{ + GTEST_LOG_(INFO) << "TearDown"; +} + +/** + * @tc.name: FsStatTest_Constructor_001 + * @tc.desc: Test FsStat::Constructor for success case + * @tc.size: SMALL + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(FsStatTest, FsStatTest_Constructor_001, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "FsStatTest-begin FsStatTest_Constructor_001"; + + auto stat = FsStat::Constructor(); + EXPECT_NE(stat, nullptr); + delete stat; + + GTEST_LOG_(INFO) << "FsStatTest-end FsStatTest_Constructor_001"; +} + +/** + * @tc.name: FsStatTest_IsBlockDevice_001 + * @tc.desc: Test FsStat::IsBlockDevice for directory + * @tc.size: SMALL + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(FsStatTest, FsStatTest_IsBlockDevice_001, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "FsStatTest-begin FsStatTest_IsBlockDevice_001"; + + auto stat = FsStat::Constructor(); + ASSERT_NE(stat, nullptr); + + stat->entity->stat_.st_mode = S_IFBLK; + EXPECT_TRUE(stat->IsBlockDevice()); + EXPECT_FALSE(stat->IsFile()); + delete stat; + + GTEST_LOG_(INFO) << "FsStatTest-end FsStatTest_IsBlockDevice_001"; +} + +/** + * @tc.name: FsStatTest_IsCharacterDevice_001 + * @tc.desc: Test FsStat::IsCharacterDevice for directory + * @tc.size: SMALL + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(FsStatTest, FsStatTest_IsCharacterDevice_001, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "FsStatTest-begin FsStatTest_IsCharacterDevice_001"; + + auto stat = FsStat::Constructor(); + ASSERT_NE(stat, nullptr); + + stat->entity->stat_.st_mode = S_IFCHR; + EXPECT_TRUE(stat->IsCharacterDevice()); + EXPECT_FALSE(stat->IsFile()); + delete stat; + + GTEST_LOG_(INFO) << "FsStatTest-end FsStatTest_IsCharacterDevice_001"; +} + +/** + * @tc.name: FsStatTest_IsDirectory_001 + * @tc.desc: Test FsStat::IsDirectory for directory + * @tc.size: SMALL + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(FsStatTest, FsStatTest_IsDirectory_001, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "FsStatTest-begin FsStatTest_IsDirectory_001"; + + auto stat = FsStat::Constructor(); + ASSERT_NE(stat, nullptr); + + stat->entity->stat_.st_mode = S_IFDIR | 0755; + EXPECT_TRUE(stat->IsDirectory()); + EXPECT_FALSE(stat->IsFile()); + delete stat; + + GTEST_LOG_(INFO) << "FsStatTest-end FsStatTest_IsDirectory_001"; +} + +/** + * @tc.name: FsStatTest_IsFIFO_001 + * @tc.desc: Test FsStat::IsFIFO for directory + * @tc.size: SMALL + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(FsStatTest, FsStatTest_IsFIFO_001, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "FsStatTest-begin FsStatTest_IsFIFO_001"; + + auto stat = FsStat::Constructor(); + ASSERT_NE(stat, nullptr); + + stat->entity->stat_.st_mode = S_IFIFO; + EXPECT_TRUE(stat->IsFIFO()); + EXPECT_FALSE(stat->IsFile()); + delete stat; + + GTEST_LOG_(INFO) << "FsStatTest-end FsStatTest_IsFIFO_001"; +} + +/** + * @tc.name: FsStatTest_IsFile_001 + * @tc.desc: Test FsStat::IsFile for regular file + * @tc.size: SMALL + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(FsStatTest, FsStatTest_IsFile_001, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "FsStatTest-begin FsStatTest_IsFile_001"; + + auto stat = FsStat::Constructor(); + ASSERT_NE(stat, nullptr); + + stat->entity->stat_.st_mode = S_IFREG | 0644; + EXPECT_TRUE(stat->IsFile()); + EXPECT_FALSE(stat->IsDirectory()); + delete stat; + + GTEST_LOG_(INFO) << "FsStatTest-end FsStatTest_IsFile_001"; +} + +/** + * @tc.name: FsStatTest_IsSocket_001 + * @tc.desc: Test FsStat::IsSocket for symbolic link + * @tc.size: SMALL + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(FsStatTest, FsStatTest_IsSocket_001, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "FsStatTest-begin FsStatTest_IsSocket_001"; + + auto stat = FsStat::Constructor(); + ASSERT_NE(stat, nullptr); + + stat->entity->stat_.st_mode = S_IFSOCK; + EXPECT_TRUE(stat->IsSocket()); + EXPECT_FALSE(stat->IsDirectory()); + delete stat; + + GTEST_LOG_(INFO) << "FsStatTest-end FsStatTest_IsSocket_001"; +} + +/** + * @tc.name: FsStatTest_IsSymbolicLink_001 + * @tc.desc: Test FsStat::IsSymbolicLink for symbolic link + * @tc.size: SMALL + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(FsStatTest, FsStatTest_IsSymbolicLink_001, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "FsStatTest-begin FsStatTest_IsSymbolicLink_001"; + + auto stat = FsStat::Constructor(); + ASSERT_NE(stat, nullptr); + + stat->entity->stat_.st_mode = S_IFLNK | 0777; + EXPECT_TRUE(stat->IsSymbolicLink()); + EXPECT_FALSE(stat->IsDirectory()); + delete stat; + + GTEST_LOG_(INFO) << "FsStatTest-end FsStatTest_IsSymbolicLink_001"; +} + +/** + * @tc.name: FsStatTest_GetIno_001 + * @tc.desc: Test FsStat::GetIno for valid inode number + * @tc.size: SMALL + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(FsStatTest, FsStatTest_GetIno_001, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "FsStatTest-begin FsStatTest_GetIno_001"; + + auto stat = FsStat::Constructor(); + ASSERT_NE(stat, nullptr); + + stat->entity->stat_.st_ino = 123456789; + EXPECT_EQ(stat->GetIno(), 123456789); + delete stat; + + GTEST_LOG_(INFO) << "FsStatTest-end FsStatTest_GetIno_001"; +} + +/** + * @tc.name: FsStatTest_GetMode_001 + * @tc.desc: Test FsStat::GetMode for permission bits + * @tc.size: SMALL + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(FsStatTest, FsStatTest_GetMode_001, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "FsStatTest-begin FsStatTest_GetMode_001"; + + auto stat = FsStat::Constructor(); + ASSERT_NE(stat, nullptr); + + stat->entity->stat_.st_mode = S_IFREG | 0755; + EXPECT_EQ(stat->GetMode(), 0755); + delete stat; + + GTEST_LOG_(INFO) << "FsStatTest-end FsStatTest_GetMode_001"; +} + +/** + * @tc.name: FsStatTest_GetUid_001 + * @tc.desc: Test FsStat::GetUid for user ID + * @tc.size: SMALL + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(FsStatTest, FsStatTest_GetUid_001, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "FsStatTest-begin FsStatTest_GetUid_001"; + + auto stat = FsStat::Constructor(); + ASSERT_NE(stat, nullptr); + + stat->entity->stat_.st_uid = 1000; + EXPECT_EQ(stat->GetUid(), 1000); + delete stat; + + GTEST_LOG_(INFO) << "FsStatTest-end FsStatTest_GetUid_001"; +} + +/** + * @tc.name: FsStatTest_GetGid_001 + * @tc.desc: Test FsStat::GetGid for group ID + * @tc.size: SMALL + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(FsStatTest, FsStatTest_GetGid_001, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "FsStatTest-begin FsStatTest_GetGid_001"; + + auto stat = FsStat::Constructor(); + ASSERT_NE(stat, nullptr); + + stat->entity->stat_.st_gid = 1000; + EXPECT_EQ(stat->GetGid(), 1000); + delete stat; + + GTEST_LOG_(INFO) << "FsStatTest-end FsStatTest_GetGid_001"; +} + +/** + * @tc.name: FsStatTest_GetSize_001 + * @tc.desc: Test FsStat::GetSize for file size + * @tc.size: SMALL + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(FsStatTest, FsStatTest_GetSize_001, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "FsStatTest-begin FsStatTest_GetSize_001"; + + auto stat = FsStat::Constructor(); + ASSERT_NE(stat, nullptr); + + stat->entity->stat_.st_size = 123456789; + EXPECT_EQ(stat->GetSize(), 123456789); + delete stat; + + GTEST_LOG_(INFO) << "FsStatTest-end FsStatTest_GetSize_001"; +} + +/** + * @tc.name: FsStatTest_GetAtime_001 + * @tc.desc: Test FsStat::GetAtime for access time in seconds + * @tc.size: SMALL + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(FsStatTest, FsStatTest_GetAtime_001, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "FsStatTest-begin FsStatTest_GetAtime_001"; + + auto stat = FsStat::Constructor(); + ASSERT_NE(stat, nullptr); + + stat->entity->stat_.st_atim.tv_sec = 1630473600; + stat->entity->stat_.st_atim.tv_nsec = 500000000; + + EXPECT_EQ(stat->GetAtime(), 1630473600); + delete stat; + + GTEST_LOG_(INFO) << "FsStatTest-end FsStatTest_GetAtime_001"; +} + +/** + * @tc.name: FsStatTest_GetMtime_001 + * @tc.desc: Test FsStat::GetMtime for modification time in seconds + * @tc.size: SMALL + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(FsStatTest, FsStatTest_GetMtime_001, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "FsStatTest-begin FsStatTest_GetMtime_001"; + + auto stat = FsStat::Constructor(); + ASSERT_NE(stat, nullptr); + + stat->entity->stat_.st_mtim.tv_sec = 1630473601; + stat->entity->stat_.st_mtim.tv_nsec = 500000000; + + EXPECT_EQ(stat->GetMtime(), 1630473601); + delete stat; + + GTEST_LOG_(INFO) << "FsStatTest-end FsStatTest_GetMtime_001"; +} + +/** + * @tc.name: FsStatTest_GetCtime_001 + * @tc.desc: Test FsStat::GetCtime for change time in seconds + * @tc.size: SMALL + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(FsStatTest, FsStatTest_GetCtime_001, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "FsStatTest-begin FsStatTest_GetCtime_001"; + + auto stat = FsStat::Constructor(); + ASSERT_NE(stat, nullptr); + + stat->entity->stat_.st_ctim.tv_sec = 1630473602; + stat->entity->stat_.st_ctim.tv_nsec = 500000000; + + EXPECT_EQ(stat->GetCtime(), 1630473602); + delete stat; + + GTEST_LOG_(INFO) << "FsStatTest-end FsStatTest_GetCtime_001"; +} + +/** + * @tc.name: FsStatTest_GetAtimeNs_001 + * @tc.desc: Test FsStat::GetAtimeNs for access time in nanoseconds + * @tc.size: SMALL + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(FsStatTest, FsStatTest_GetAtimeNs_001, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "FsStatTest-begin FsStatTest_GetAtimeNs_001"; + + auto stat = FsStat::Constructor(); + ASSERT_NE(stat, nullptr); + + stat->entity->stat_.st_atim.tv_sec = 1630473600; + stat->entity->stat_.st_atim.tv_nsec = 500000000; + + int64_t expected = 1630473600LL * 1000000000 + 500000000; + EXPECT_EQ(stat->GetAtimeNs(), expected); + delete stat; + + GTEST_LOG_(INFO) << "FsStatTest-end FsStatTest_GetAtimeNs_001"; +} + +/** + * @tc.name: FsStatTest_GetMtimeNs_001 + * @tc.desc: Test FsStat::GetMtimeNs for modification time in nanoseconds + * @tc.size: SMALL + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(FsStatTest, FsStatTest_GetMtimeNs_001, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "FsStatTest-begin FsStatTest_GetMtimeNs_001"; + + auto stat = FsStat::Constructor(); + ASSERT_NE(stat, nullptr); + + stat->entity->stat_.st_mtim.tv_sec = 1630473601; + stat->entity->stat_.st_mtim.tv_nsec = 500000000; + + int64_t expected = 1630473601LL * 1000000000 + 500000000; + EXPECT_EQ(stat->GetMtimeNs(), expected); + delete stat; + + GTEST_LOG_(INFO) << "FsStatTest-end FsStatTest_GetMtimeNs_001"; +} + +/** + * @tc.name: FsStatTest_GetCtimeNs_001 + * @tc.desc: Test FsStat::GetCtimeNs for change time in nanoseconds + * @tc.size: SMALL + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(FsStatTest, FsStatTest_GetCtimeNs_001, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "FsStatTest-begin FsStatTest_GetCtimeNs_001"; + + auto stat = FsStat::Constructor(); + ASSERT_NE(stat, nullptr); + + stat->entity->stat_.st_ctim.tv_sec = 1630473602; + stat->entity->stat_.st_ctim.tv_nsec = 500000000; + + int64_t expected = 1630473602LL * 1000000000 + 500000000; + EXPECT_EQ(stat->GetCtimeNs(), expected); + delete stat; + + GTEST_LOG_(INFO) << "FsStatTest-end FsStatTest_GetCtimeNs_001"; +} + +} \ No newline at end of file diff --git a/interfaces/test/unittest/js/mod_fs/properties/access_core_mock_test.cpp b/interfaces/test/unittest/js/mod_fs/properties/access_core_mock_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..4d9355d9cdbb3caf5449287cfca6496bf34982c3 --- /dev/null +++ b/interfaces/test/unittest/js/mod_fs/properties/access_core_mock_test.cpp @@ -0,0 +1,172 @@ +/* + * Copyright (C) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#include "access_core.h" +#include "uv_fs_mock.h" + +#include + +namespace OHOS::FileManagement::ModuleFileIO::Test { +using namespace testing; +using namespace testing::ext; +using namespace std; + +class AccessCoreMockTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); + static inline std::shared_ptr uvMock = nullptr; + const string DISTRIBUTED_FILE_PREFIX = "/data/storage/el2/distributedfiles"; +}; + +void AccessCoreMockTest::SetUpTestCase(void) +{ + GTEST_LOG_(INFO) << "SetUpTestCase"; + uvMock = std::make_shared(); + Uvfs::ins = uvMock; +} + +void AccessCoreMockTest::TearDownTestCase(void) +{ + Uvfs::ins = nullptr; + uvMock = nullptr; + GTEST_LOG_(INFO) << "TearDownTestCase"; +} + +void AccessCoreMockTest::SetUp(void) +{ + GTEST_LOG_(INFO) << "SetUp"; +} + +void AccessCoreMockTest::TearDown(void) +{ + GTEST_LOG_(INFO) << "TearDown"; +} + +/** + * @tc.name: AccessCoreMockTest_DoAccess_001 + * @tc.desc: Test function of AccessCore::ValidAccessArgs interface for FALSE. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(AccessCoreMockTest, AccessCoreMockTest_DoAccess_001, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "NClassTest-begin AccessCoreMockTest_DoAccess_001"; + + std::string path = "TEST"; + std::optional mode; + + EXPECT_CALL(*uvMock, uv_fs_access(_, _, _, _, _)).WillOnce(Return(-1)); + auto res = AccessCore::DoAccess(path, mode); + EXPECT_EQ(res.IsSuccess(), false); + + GTEST_LOG_(INFO) << "NClassTest-end AccessCoreMockTest_DoAccess_001"; +} + +/** + * @tc.name: AccessCoreMockTest_DoAccess_002 + * @tc.desc: Test function of AccessCore::ValidAccessArgs interface for SUCCESS. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(AccessCoreMockTest, AccessCoreMockTest_DoAccess_002, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "NClassTest-begin AccessCoreMockTest_DoAccess_002"; + + std::string path = "TEST"; + std::optional mode; + + EXPECT_CALL(*uvMock, uv_fs_access(_, _, _, _, _)).WillOnce(Return(0)); + + auto res = AccessCore::DoAccess(path, mode); + EXPECT_EQ(res.IsSuccess(), true); + + GTEST_LOG_(INFO) << "NClassTest-end AccessCoreMockTest_DoAccess_002"; +} + +/** + * @tc.name: AccessCoreMockTest_DoAccess_003 + * @tc.desc: Test function of AccessCore::DoAccess interface for FALSE. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(AccessCoreMockTest, AccessCoreMockTest_DoAccess_003, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "NClassTest-begin AccessCoreMockTest_DoAccess_003"; + + std::string path = "TEST"; + AccessModeType mode = AccessModeType::EXIST; + AccessFlag flag = DEFAULT_FLAG; + + EXPECT_CALL(*uvMock, uv_fs_access(_, _, _, _, _)).WillOnce(Return(-1)); + auto res = AccessCore::DoAccess(path, mode, flag); + EXPECT_EQ(res.IsSuccess(), false); + + GTEST_LOG_(INFO) << "NClassTest-end AccessCoreMockTest_DoAccess_003"; +} + +/** + * @tc.name: AccessCoreMockTest_DoAccess_004 + * @tc.desc: Test function of AccessCore::DoAccess interface for SUCCESS. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(AccessCoreMockTest, AccessCoreMockTest_DoAccess_004, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "NClassTest-begin AccessCoreMockTest_DoAccess_004"; + + std::string path = "TEST"; + AccessModeType mode = AccessModeType::EXIST; + AccessFlag flag = DEFAULT_FLAG; + + EXPECT_CALL(*uvMock, uv_fs_access(_, _, _, _, _)).WillOnce(Return(0)); + + auto res = AccessCore::DoAccess(path, mode, flag); + EXPECT_EQ(res.IsSuccess(), true); + + GTEST_LOG_(INFO) << "NClassTest-end AccessCoreMockTest_DoAccess_004"; +} + +/** + * @tc.name: AccessCoreMockTest_DoAccess_005 + * @tc.desc: Test function of AccessCore::DoAccess interface for success. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(AccessCoreMockTest, AccessCoreMockTest_DoAccess_005, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "AccessCoreMockTest-begin AccessCoreMockTest_DoAccess_005"; + + std::string path = DISTRIBUTED_FILE_PREFIX; + AccessModeType mode = AccessModeType::EXIST; + AccessFlag flag = LOCAL_FLAG; + + EXPECT_CALL(*uvMock, uv_fs_access(_, _, _, _, _)).WillOnce(Return(0)); + + auto res = AccessCore::DoAccess(path, mode, flag); + EXPECT_EQ(res.IsSuccess(), true); + + GTEST_LOG_(INFO) << "AccessCoreMockTest-end AccessCoreMockTest_DoAccess_005"; +} + +} // OHOS::FileManagement::ModuleFileIO::Test \ No newline at end of file diff --git a/interfaces/test/unittest/js/mod_fs/properties/access_core_test.cpp b/interfaces/test/unittest/js/mod_fs/properties/access_core_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b7966bd3cb40a3ef28a87366b7d209e395d31290 --- /dev/null +++ b/interfaces/test/unittest/js/mod_fs/properties/access_core_test.cpp @@ -0,0 +1,250 @@ +/* + * Copyright (C) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#include "access_core.h" + +#include +#include + + +namespace OHOS::FileManagement::ModuleFileIO::Test { +using namespace testing; +using namespace testing::ext; +using namespace std; + +const mode_t DIR_PERMISSIONS = 0755; + +class AccessCoreTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); + const string CLOUDDISK_FILE_PREFIX = "/data/storage/el2/cloud"; + const string DISTRIBUTED_FILE_PREFIX = "/data/storage/el2/distributedfiles"; + const string CLOUD_FILE_LOCATION = "user.cloud.location"; + const string POSITION_LOCAL = "1"; + const string POSITION_BOTH = "2"; +}; + +void AccessCoreTest::SetUpTestCase(void) +{ + GTEST_LOG_(INFO) << "SetUpTestCase"; +} + +void AccessCoreTest::TearDownTestCase(void) +{ + GTEST_LOG_(INFO) << "TearDownTestCase"; +} + +void AccessCoreTest::SetUp(void) +{ + GTEST_LOG_(INFO) << "SetUp"; +} + +void AccessCoreTest::TearDown(void) +{ + GTEST_LOG_(INFO) << "TearDown"; +} + +// 递归创建多级目录的辅助函数 +bool CreateDirectoryRecursive(const std::string& path) +{ + if (path.empty()) { + return false; + } + + size_t pos = 0; + std::string dir; + if (path[0] == '/') { + dir += '/'; + pos++; + } + + while ((pos = path.find('/', pos)) != std::string::npos) + { + dir = path.substr(0, pos++); + if (dir.empty()) { + continue; + } + if (mkdir(dir.c_str(), DIR_PERMISSIONS) == -1) { + if (errno != EEXIST) { + return false; + } + } + } + + if (mkdir(path.c_str(), DIR_PERMISSIONS) == -1 && errno != EEXIST) + { + return false; + } + return true; +} + +/** + * @tc.name: AccessCoreTest_DoAccess_001 + * @tc.desc: Test function of AccessCore::DoAccess interface for ERROR. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(AccessCoreTest, AccessCoreTest_DoAccess_001, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "AccessCoreTest-begin AccessCoreTest_DoAccess_001"; + + std::string path; + std::optional mode; + + auto res = AccessCore::DoAccess(path, mode); + EXPECT_EQ(res.IsSuccess(), false); + + GTEST_LOG_(INFO) << "AccessCoreTest-end AccessCoreTest_DoAccess_001"; +} + +/** + * @tc.name: AccessCoreTest_DoAccess_002 + * @tc.desc: Test function of AccessCore::DoAccess interface for ERROR. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(AccessCoreTest, AccessCoreTest_DoAccess_002, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "AccessCoreTest-begin AccessCoreTest_DoAccess_002"; + + std::string path = ""; + AccessModeType mode = AccessModeType::EXIST; + AccessFlag flag = DEFAULT_FLAG; + + auto res = AccessCore::DoAccess(path, mode, flag); + EXPECT_EQ(res.IsSuccess(), false); + + GTEST_LOG_(INFO) << "AccessCoreTest-end AccessCoreTest_DoAccess_002"; +} + +/** + * @tc.name: AccessCoreTest_DoAccess_003 + * @tc.desc: Test function of AccessCore::DoAccess interface for ERROR. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(AccessCoreTest, AccessCoreTest_DoAccess_003, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "AccessCoreTest-begin AccessCoreTest_DoAccess_003"; + + std::string path = "test"; + std::optional mode = std::make_optional(AccessModeType::ERROR); + + auto res = AccessCore::DoAccess(path, mode); + EXPECT_EQ(res.IsSuccess(), false); + + GTEST_LOG_(INFO) << "AccessCoreTest-end AccessCoreTest_DoAccess_003"; +} + +/** + * @tc.name: AccessCoreTest_DoAccess_004 + * @tc.desc: Test function of AccessCore::DoAccess interface for SUCCESS. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(AccessCoreTest, AccessCoreTest_DoAccess_004, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "AccessCoreTest-begin AccessCoreTest_DoAccess_004"; + + std::string path = CLOUDDISK_FILE_PREFIX; + AccessModeType mode = AccessModeType::EXIST; + AccessFlag flag = LOCAL_FLAG; + + auto res = AccessCore::DoAccess(path, mode, flag); + EXPECT_EQ(res.IsSuccess(), true); + + GTEST_LOG_(INFO) << "AccessCoreTest-end AccessCoreTest_DoAccess_004"; +} + +/** + * @tc.name: AccessCoreTest_DoAccess_005 + * @tc.desc: Test function of AccessCore::DoAccess interface for ERROR. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(AccessCoreTest, AccessCoreTest_DoAccess_005, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "AccessCoreTest-begin AccessCoreTest_DoAccess_005"; + + std::string path = CLOUDDISK_FILE_PREFIX; + AccessModeType mode = AccessModeType::EXIST; + AccessFlag flag = LOCAL_FLAG; + + ASSERT_TRUE(CreateDirectoryRecursive(path)); + auto re = setxattr(path.c_str(), CLOUD_FILE_LOCATION.c_str(), POSITION_LOCAL.c_str(), POSITION_LOCAL.size(), 0); + ASSERT_NE(re, -1); + + auto res = AccessCore::DoAccess(path, mode, flag); + EXPECT_EQ(res.IsSuccess(), true); + + GTEST_LOG_(INFO) << "AccessCoreTest-end AccessCoreTest_DoAccess_005"; +} + +/** + * @tc.name: AccessCoreTest_DoAccess_006 + * @tc.desc: Test function of AccessCore::DoAccess interface for SUCCESS. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(AccessCoreTest, AccessCoreTest_DoAccess_006, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "AccessCoreTest-begin AccessCoreTest_DoAccess_006"; + + std::string path = "test"; + AccessModeType mode = AccessModeType::EXIST; + AccessFlag flag = LOCAL_FLAG; + + auto res = AccessCore::DoAccess(path, mode, flag); + EXPECT_EQ(res.IsSuccess(), true); + + GTEST_LOG_(INFO) << "AccessCoreTest-end AccessCoreTest_DoAccess_006"; +} + +/** + * @tc.name: AccessCoreTest_DoAccess_007 + * @tc.desc: Test function of AccessCore::DoAccess interface for ERROR. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(AccessCoreTest, AccessCoreTest_DoAccess_007, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "AccessCoreTest-begin AccessCoreTest_DoAccess_007"; + + std::string path = CLOUDDISK_FILE_PREFIX; + AccessModeType mode = AccessModeType::EXIST; + AccessFlag flag = LOCAL_FLAG; + + ASSERT_TRUE(CreateDirectoryRecursive(path)); + auto re = setxattr(path.c_str(), CLOUD_FILE_LOCATION.c_str(), POSITION_BOTH.c_str(), POSITION_BOTH.size(), 0); + ASSERT_NE(re, -1); + + auto res = AccessCore::DoAccess(path, mode, flag); + EXPECT_EQ(res.IsSuccess(), true); + + GTEST_LOG_(INFO) << "AccessCoreTest-end AccessCoreTest_DoAccess_007"; +} + +} // OHOS::FileManagement::ModuleFileIO::Test \ No newline at end of file diff --git a/interfaces/test/unittest/js/mod_fs/properties/close_core_test.cpp b/interfaces/test/unittest/js/mod_fs/properties/close_core_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..866d9cbe0b3179c90eaafe0e68a6a8e9d054cf9b --- /dev/null +++ b/interfaces/test/unittest/js/mod_fs/properties/close_core_test.cpp @@ -0,0 +1,113 @@ +/* +* Copyright (c) 2025 Huawei Device Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +#include +#include "close_core.h" +#include "open_core.h" + +#define FILE_PATH "/data/test/CloseCoreTest.txt" + +namespace OHOS { +namespace FileManagement { +namespace ModuleFileIO { +using namespace std; +class CloseCoreTest : public testing::Test { +public: + static void SetUpTestCase(void) + { + int32_t fd = open(FILE_PATH, CREATE | O_RDWR, 0644); + close(fd); + }; + static void TearDownTestCase() + { + rmdir(FILE_PATH); + }; + void SetUp() {}; + void TearDown() {}; +}; + +/** +* @tc.name: DoCloseTestFd_0001 +* @tc.desc: Test function of DoClose() interface for invalid arguments. +* @tc.size: MEDIUM +* @tc.type: FUNC +* @tc.level Level 1 +* @tc.require: AR000IGDNF +*/ +HWTEST_F(CloseCoreTest, DoCloseTestFd_0001, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "CloseCoreTest-begin DoCloseTestFd_0001"; + auto ret = CloseCore::DoClose(-1); + EXPECT_FALSE(ret.IsSuccess()); + + auto err = ret.GetError(); + EXPECT_EQ(err.GetErrNo(), 13900020); + + + GTEST_LOG_(INFO) << "CloseCoreTest-end DoCloseTestFd_0001"; +} + +/** +* @tc.name: DoCloseTestFile_0001 +* @tc.desc: Test function of DoClose() interface for success. +* @tc.size: MEDIUM +* @tc.type: FUNC +* @tc.level Level 1 +* @tc.require: AR000IGDNF +*/ +HWTEST_F(CloseCoreTest, DoCloseTestFile_0001, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "CloseCoreTest-begin DoCloseTestFile_0001"; + auto fileRes = OpenCore::DoOpen(FILE_PATH); + if (!fileRes.IsSuccess()) { + ASSERT_TRUE(false); + } + FsFile *file = fileRes.GetData().value(); + auto ret = CloseCore::DoClose(file); + EXPECT_TRUE(ret.IsSuccess()); + + GTEST_LOG_(INFO) << "CloseCoreTest-end DoCloseTestFile_0001"; +} + +/** +* @tc.name: DoCloseTestFile_0002 +* @tc.desc: Test function of DoClose() interface for failed get fd. +* @tc.size: MEDIUM +* @tc.type: FUNC +* @tc.level Level 1 +* @tc.require: AR000IGDNF +*/ +HWTEST_F(CloseCoreTest, DoCloseTestFile_0002, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "CloseCoreTest-begin DoCloseTestFile_0002"; + auto fileRes = OpenCore::DoOpen(FILE_PATH); + if (!fileRes.IsSuccess()) { + ASSERT_TRUE(false); + } + FsFile *file = fileRes.GetData().value(); + auto ret = CloseCore::DoClose(file); + EXPECT_TRUE(ret.IsSuccess()); + + ret = CloseCore::DoClose(file); + EXPECT_FALSE(ret.IsSuccess()); + auto err = ret.GetError(); + EXPECT_EQ(err.GetErrNo(), 13900020); + + GTEST_LOG_(INFO) << "CloseCoreTest-end DoCloseTestFile_0002"; +} + +} +} +} \ No newline at end of file diff --git a/interfaces/test/unittest/js/mod_fs/properties/copy_file_core_mock_test.cpp b/interfaces/test/unittest/js/mod_fs/properties/copy_file_core_mock_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..af533602a0dff305542607889773d097d046636d --- /dev/null +++ b/interfaces/test/unittest/js/mod_fs/properties/copy_file_core_mock_test.cpp @@ -0,0 +1,408 @@ +/* + * Copyright (C) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "copy_file_core.h" +#include "uv_fs_mock.h" + +#include + +namespace OHOS::FileManagement::ModuleFileIO::Test { +using namespace testing; +using namespace testing::ext; +using namespace std; + +class CopyFileCoreTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); + static inline shared_ptr uvfs = nullptr; +}; + +void CopyFileCoreTest::SetUpTestCase(void) +{ + uvfs = std::make_shared(); + Uvfs::ins = uvfs; + GTEST_LOG_(INFO) << "SetUpTestCase"; +} + +void CopyFileCoreTest::TearDownTestCase(void) +{ + Uvfs::ins = nullptr; + uvfs = nullptr; + GTEST_LOG_(INFO) << "TearDownTestCase"; +} + +void CopyFileCoreTest::SetUp(void) +{ + GTEST_LOG_(INFO) << "SetUp"; +} + +void CopyFileCoreTest::TearDown(void) +{ + GTEST_LOG_(INFO) << "TearDown"; +} + +/** + * @tc.name: CopyFileCoreTest_DoCopyFile_001 + * @tc.desc: Test function of CopyFileCore::ValidMode interface for FALSE. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(CopyFileCoreTest, CopyFileCoreTest_DoCopyFile_001, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "CopyFileCoreTest-begin CopyFileCoreTest_DoCopyFile_001"; + + FileInfo src; + FileInfo dest; + optional mode = std::make_optional(1); + + auto res = CopyFileCore::DoCopyFile(src, dest, mode); + EXPECT_EQ(res.IsSuccess(), false); + + GTEST_LOG_(INFO) << "CopyFileCoreTest-end CopyFileCoreTest_DoCopyFile_001"; +} + +/** + * @tc.name: CopyFileCoreTest_DoCopyFile_003 + * @tc.desc: Test function of CopyFileCore::OpenFile.OpenCore interface for FALSE. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(CopyFileCoreTest, CopyFileCoreTest_DoCopyFile_003, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "CopyFileCoreTest-begin CopyFileCoreTest_DoCopyFile_003"; + + FileInfo src; + FileInfo dest; + src.isPath = true; + dest.isPath = false; + + EXPECT_CALL(*uvfs, uv_fs_open(_, _, _, _, _, _)).Times(1).WillOnce(Return(-1)); + + auto res = CopyFileCore::DoCopyFile(src, dest); + EXPECT_EQ(res.IsSuccess(), false); + + GTEST_LOG_(INFO) << "CopyFileCoreTest-end CopyFileCoreTest_DoCopyFile_003"; +} + +/** + * @tc.name: CopyFileCoreTest_DoCopyFile_004 + * @tc.desc: Test function of CopyFileCore::OpenFile.OpenCore interface for FALSE. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(CopyFileCoreTest, CopyFileCoreTest_DoCopyFile_004, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "CopyFileCoreTest-begin CopyFileCoreTest_DoCopyFile_004"; + + FileInfo src; + FileInfo dest; + src.isPath = true; + dest.isPath = false; + src.fdg = make_unique(1); + + EXPECT_CALL(*uvfs, uv_fs_open(_, _, _, _, _, _)).Times(1).WillOnce(Return(1)); + + auto res = CopyFileCore::DoCopyFile(src, dest); + EXPECT_EQ(res.IsSuccess(), false); + + GTEST_LOG_(INFO) << "CopyFileCoreTest-end CopyFileCoreTest_DoCopyFile_004"; +} + +/** + * @tc.name: CopyFileCoreTest_DoCopyFile_005 + * @tc.desc: Test function of CopyFileCore::OpenFile.OpenCore interface for FALSE. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(CopyFileCoreTest, CopyFileCoreTest_DoCopyFile_005, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "CopyFileCoreTest-begin CopyFileCoreTest_DoCopyFile_005"; + + FileInfo src; + FileInfo dest; + src.isPath = false; + dest.isPath = true; + int fd = open("test.txt", O_RDWR | O_CREAT, S_IRUSR | S_IWUSR); + ASSERT_NE(fd, -1); + src.fdg = make_unique(fd); + + EXPECT_CALL(*uvfs, uv_fs_open(_, _, _, _, _, _)).Times(1).WillOnce(Return(-1)); + + auto res = CopyFileCore::DoCopyFile(src, dest); + EXPECT_EQ(res.IsSuccess(), false); + close(fd); + + GTEST_LOG_(INFO) << "CopyFileCoreTest-end CopyFileCoreTest_DoCopyFile_005"; +} + +/** + * @tc.name: CopyFileCoreTest_DoCopyFile_006 + * @tc.desc: Test function of CopyFileCore::OpenFile.OpenCore interface for SUCCESS. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(CopyFileCoreTest, CopyFileCoreTest_DoCopyFile_006, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "CopyFileCoreTest-begin CopyFileCoreTest_DoCopyFile_006"; + + FileInfo src; + FileInfo dest; + src.isPath = false; + dest.isPath = true; + int fd = open("test.txt", O_RDWR | O_CREAT, S_IRUSR | S_IWUSR); + ASSERT_NE(fd, -1); + src.fdg = make_unique(fd); + + EXPECT_CALL(*uvfs, uv_fs_open(_, _, _, _, _, _)).Times(1).WillOnce(Return(1)); + + auto res = CopyFileCore::DoCopyFile(src, dest); + EXPECT_EQ(res.IsSuccess(), true); + close(fd); + + GTEST_LOG_(INFO) << "CopyFileCoreTest-end CopyFileCoreTest_DoCopyFile_006"; +} + +/** + * @tc.name: CopyFileCoreTest_DoCopyFile_007 + * @tc.desc: Test function of CopyFileCore::OpenFile.TruncateCore interface for FALSE. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(CopyFileCoreTest, CopyFileCoreTest_DoCopyFile_007, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "CopyFileCoreTest-begin CopyFileCoreTest_DoCopyFile_007"; + + FileInfo src; + FileInfo dest; + src.isPath = false; + dest.isPath = false; + int fd = open("test.txt", O_RDWR | O_CREAT, S_IRUSR | S_IWUSR); + ASSERT_NE(fd, -1); + src.fdg = make_unique(fd); + dest.fdg = make_unique(fd); + + EXPECT_CALL(*uvfs, uv_fs_ftruncate(_, _, _, _, _)).Times(1).WillOnce(Return(-1)); + + auto res = CopyFileCore::DoCopyFile(src, dest); + EXPECT_EQ(res.IsSuccess(), false); + close(fd); + + GTEST_LOG_(INFO) << "CopyFileCoreTest-end CopyFileCoreTest_DoCopyFile_007"; +} + +/** + * @tc.name: CopyFileCoreTest_DoCopyFile_008 + * @tc.desc: Test function of CopyFileCore::OpenFile.TruncateCore interface for FALSE. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(CopyFileCoreTest, CopyFileCoreTest_DoCopyFile_008, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "CopyFileCoreTest-begin CopyFileCoreTest_DoCopyFile_008"; + + FileInfo src; + FileInfo dest; + src.isPath = false; + dest.isPath = false; + int fd = open("test.txt", O_RDWR | O_CREAT, S_IRUSR | S_IWUSR); + ASSERT_NE(fd, -1); + src.fdg = make_unique(fd); + dest.fdg = make_unique(); + + EXPECT_CALL(*uvfs, uv_fs_ftruncate(_, _, _, _, _)).Times(1).WillOnce(Return(1)); + + auto res = CopyFileCore::DoCopyFile(src, dest); + EXPECT_EQ(res.IsSuccess(), false); + close(fd); + + GTEST_LOG_(INFO) << "CopyFileCoreTest-end CopyFileCoreTest_DoCopyFile_008"; +} + +/** + * @tc.name: CopyFileCoreTest_DoCopyFile_009 + * @tc.desc: Test function of CopyFileCore::OpenFile.TruncateCore interface for SUCCESS. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(CopyFileCoreTest, CopyFileCoreTest_DoCopyFile_009, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "CopyFileCoreTest-begin CopyFileCoreTest_DoCopyFile_009"; + + FileInfo src; + FileInfo dest; + src.isPath = false; + dest.isPath = false; + + int srcfd = open("src.txt", O_RDWR | O_CREAT, S_IRUSR | S_IWUSR); + int destfd = open("dest.txt", O_RDWR | O_CREAT, S_IRUSR | S_IWUSR); + ASSERT_NE(srcfd, -1); + ASSERT_NE(destfd, -1); + src.fdg = make_unique(srcfd); + dest.fdg = make_unique(destfd); + + EXPECT_CALL(*uvfs, uv_fs_ftruncate(_, _, _, _, _)).Times(1).WillOnce(Return(1)); + + auto res = CopyFileCore::DoCopyFile(src, dest); + EXPECT_EQ(res.IsSuccess(), true); + close(srcfd); + close(destfd); + + GTEST_LOG_(INFO) << "CopyFileCoreTest-end CopyFileCoreTest_DoCopyFile_009"; +} + +/** + * @tc.name: CopyFileCoreTest_DoCopyFile_0010 + * @tc.desc: Test function of CopyFileCore::OpenFile.SendFileCore interface for false. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(CopyFileCoreTest, CopyFileCoreTest_DoCopyFile_0010, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "CopyFileCoreTest-begin CopyFileCoreTest_DoCopyFile_0010"; + + FileInfo src; + FileInfo dest; + src.isPath = false; + dest.isPath = true; + + int srcfd = open("src.txt", O_RDWR | O_CREAT, S_IRUSR | S_IWUSR); + ASSERT_NE(srcfd, -1); + const char* data = "Hello, World!"; + ssize_t len = write(srcfd, data, strlen(data)); + ASSERT_NE(len, -1); + src.fdg = make_unique(srcfd); + + EXPECT_CALL(*uvfs, uv_fs_open(_, _, _, _, _, _)).Times(1).WillOnce(Return(1)); + EXPECT_CALL(*uvfs, uv_fs_sendfile(_, _, _, _, _, _, _)).Times(1).WillOnce(Return(-1)); + + auto res = CopyFileCore::DoCopyFile(src, dest); + EXPECT_EQ(res.IsSuccess(), false); + close(srcfd); + + GTEST_LOG_(INFO) << "CopyFileCoreTest-end CopyFileCoreTest_DoCopyFile_0010"; +} + +/** + * @tc.name: CopyFileCoreTest_DoCopyFile_0011 + * @tc.desc: Test function of CopyFileCore::OpenFile.SendFileCore interface for false. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(CopyFileCoreTest, CopyFileCoreTest_DoCopyFile_0011, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "CopyFileCoreTest-begin CopyFileCoreTest_DoCopyFile_0011"; + + FileInfo src; + FileInfo dest; + src.isPath = false; + dest.isPath = true; + + int srcfd = open("src.txt", O_RDWR | O_CREAT, S_IRUSR | S_IWUSR); + ASSERT_NE(srcfd, -1); + const char* data = "Hello, World!"; + ssize_t len = write(srcfd, data, strlen(data)); + ASSERT_NE(len, -1); + src.fdg = make_unique(srcfd); + + EXPECT_CALL(*uvfs, uv_fs_open(_, _, _, _, _, _)).Times(1).WillOnce(Return(1)); + EXPECT_CALL(*uvfs, uv_fs_sendfile(_, _, _, _, _, _, _)).Times(1).WillOnce(Return(len + 1)); + + auto res = CopyFileCore::DoCopyFile(src, dest); + EXPECT_EQ(res.IsSuccess(), false); + close(srcfd); + + GTEST_LOG_(INFO) << "CopyFileCoreTest-end CopyFileCoreTest_DoCopyFile_0011"; +} + +/** + * @tc.name: CopyFileCoreTest_DoCopyFile_0012 + * @tc.desc: Test function of CopyFileCore::OpenFile.SendFileCore interface for SUCCESS. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(CopyFileCoreTest, CopyFileCoreTest_DoCopyFile_0012, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "CopyFileCoreTest-begin CopyFileCoreTest_DoCopyFile_0012"; + + FileInfo src; + FileInfo dest; + src.isPath = false; + dest.isPath = true; + + int srcfd = open("src.txt", O_RDWR | O_CREAT, S_IRUSR | S_IWUSR); + ASSERT_NE(srcfd, -1); + const char* data = "Hello, World!"; + ssize_t len = write(srcfd, data, strlen(data)); + ASSERT_NE(len, -1); + src.fdg = make_unique(srcfd); + + EXPECT_CALL(*uvfs, uv_fs_open(_, _, _, _, _, _)).Times(1).WillOnce(Return(1)); + EXPECT_CALL(*uvfs, uv_fs_sendfile(_, _, _, _, _, _, _)).Times(1).WillOnce(Return(len)); + + auto res = CopyFileCore::DoCopyFile(src, dest); + EXPECT_EQ(res.IsSuccess(), true); + close(srcfd); + + GTEST_LOG_(INFO) << "CopyFileCoreTest-end CopyFileCoreTest_DoCopyFile_0012"; +} + +/** + * @tc.name: CopyFileCoreTest_DoCopyFile_0013 + * @tc.desc: Test function of CopyFileCore::OpenFile.SendFileCore interface for FALSE. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(CopyFileCoreTest, CopyFileCoreTest_DoCopyFile_0013, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "CopyFileCoreTest-begin CopyFileCoreTest_DoCopyFile_0013"; + + FileInfo src; + FileInfo dest; + src.isPath = false; + dest.isPath = true; + + int srcfd = open("src.txt", O_RDWR | O_CREAT, S_IRUSR | S_IWUSR); + ASSERT_NE(srcfd, -1); + const char* data = "Hello, World!"; + ssize_t len = write(srcfd, data, strlen(data)); + ASSERT_NE(len, -1); + src.fdg = make_unique(srcfd); + + EXPECT_CALL(*uvfs, uv_fs_open(_, _, _, _, _, _)).Times(1).WillOnce(Return(1)); + EXPECT_CALL(*uvfs, uv_fs_sendfile(_, _, _, _, _, _, _)).Times(1).WillOnce(Return(0)); + + auto res = CopyFileCore::DoCopyFile(src, dest); + EXPECT_EQ(res.IsSuccess(), false); + close(srcfd); + + GTEST_LOG_(INFO) << "CopyFileCoreTest-end CopyFileCoreTest_DoCopyFile_0013"; +} + +} // namespace OHOS::FileManagement::ModuleFileIO::Test \ No newline at end of file diff --git a/interfaces/test/unittest/js/mod_fs/properties/copy_file_core_test.cpp b/interfaces/test/unittest/js/mod_fs/properties/copy_file_core_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8d14cda0e678a7535acb7e9908dc71075e572693 --- /dev/null +++ b/interfaces/test/unittest/js/mod_fs/properties/copy_file_core_test.cpp @@ -0,0 +1,98 @@ +/* + * Copyright (C) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "copy_file_core.h" + +#include + +namespace OHOS::FileManagement::ModuleFileIO::Test { +using namespace testing; +using namespace testing::ext; +using namespace std; + +class CopyFileCoreMockTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); +}; + +void CopyFileCoreMockTest::SetUpTestCase(void) +{ + GTEST_LOG_(INFO) << "SetUpTestCase"; +} + +void CopyFileCoreMockTest::TearDownTestCase(void) +{ + GTEST_LOG_(INFO) << "TearDownTestCase"; +} + +void CopyFileCoreMockTest::SetUp(void) +{ + GTEST_LOG_(INFO) << "SetUp"; +} + +void CopyFileCoreMockTest::TearDown(void) +{ + GTEST_LOG_(INFO) << "TearDown"; +} + +/** + * @tc.name: CopyFileCoreMockTest_DoCopyFile_001 + * @tc.desc: Test function of CopyFileCore::ValidMode interface for FALSE. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(CopyFileCoreMockTest, CopyFileCoreMockTest_DoCopyFile_001, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "CopyFileCoreMockTest-begin CopyFileCoreMockTest_DoCopyFile_001"; + + FileInfo src; + FileInfo dest; + optional mode = std::make_optional(1); + + auto res = CopyFileCore::DoCopyFile(src, dest, mode); + EXPECT_EQ(res.IsSuccess(), false); + + GTEST_LOG_(INFO) << "CopyFileCoreMockTest-end CopyFileCoreMockTest_DoCopyFile_001"; +} + +/** + * @tc.name: CopyFileCoreMockTest_DoCopyFile_002 + * @tc.desc: Test function of CopyFileCore::ValidMode interface for FALSE. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(CopyFileCoreMockTest, CopyFileCoreMockTest_DoCopyFile_002, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "CopyFileCoreMockTest-begin CopyFileCoreMockTest_DoCopyFile_002"; + + FileInfo src; + FileInfo dest; + src.isPath = true; + dest.isPath = true; + src.path = std::make_unique(1); + dest.path = std::make_unique(1); + + auto res = CopyFileCore::DoCopyFile(src, dest); + EXPECT_EQ(res.IsSuccess(), false); + + GTEST_LOG_(INFO) << "CopyFileCoreMockTest-end CopyFileCoreMockTest_DoCopyFile_002"; +} + +} // namespace OHOS::FileManagement::ModuleFileIO::Test \ No newline at end of file diff --git a/interfaces/test/unittest/js/mod_fs/properties/listfile_core_test.cpp b/interfaces/test/unittest/js/mod_fs/properties/listfile_core_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..dbea771a41d6ea5c05ff61771b6489d5fe07886d --- /dev/null +++ b/interfaces/test/unittest/js/mod_fs/properties/listfile_core_test.cpp @@ -0,0 +1,525 @@ +/* +* Copyright (c) 2025 Huawei Device Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +#include +#include +#include +#include "listfile_core.h" + +#define DIR_PATH "/data/test/ListFileCoreTest" +#define EMPTY_PATH "/data/test/Empty" + +namespace OHOS { +namespace FileManagement { +namespace ModuleFileIO { +using namespace std; +namespace fs = std::filesystem; + +static void create_file(const fs::path& path, const std::vector& data, bool binary = true) +{ + fs::create_directories(path.parent_path()); // 确保目录存在 + std::ofstream file(path, binary ? std::ios::binary : std::ios::out); + if (!file) { + GTEST_LOG_(INFO) << "create_directories failed"; + return; + } + file.write(reinterpret_cast(data.data()), data.size()); + GTEST_LOG_(INFO) << "create_directories success"; +} + +static void WriteBuffer(const string filename) +{ + const int targetSize = 1024; + std::vector buffer(targetSize, 0); + std::ofstream file(filename, std::ios::binary); + file.write(buffer.data(), buffer.size()); +} + +class ListFileCoreTest : public testing::Test { +public: + static void SetUpTestCase(void) + { + fs::create_directory(EMPTY_PATH); + const std::vector directories = { + "/data/test/ListFileCoreTest", // 单级目录 + "/data/test/ListFileCoreTest/level1", // 二级目录 + "/data/test/ListFileCoreTest/level1/level2" // 三级目录 + }; + + // 为每个文件类型创建3个文件 + for (int i = 0; i < 3; ++i) { + create_file(directories[i] / ("text_" + std::to_string(i + 1) + ".txt"), + {'F', 'i', 'l', 'e', ' ', char('0' + i + 1)}, false); + + create_file(directories[i] / ("image_" + std::to_string(i + 1) + ".png"), + {0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A}); + + create_file(directories[i] / ("photo_" + std::to_string(i + 1) + ".jpg"), + {0xFF, 0xD8, 0xFF, 0xE0, 0x00, 0x10, 0x4A, 0x46}); + + create_file(directories[i] / ("data_" + std::to_string(i + 1) + ".data"), + {0xAB, 0xCD, 0xEF, char(i), char(i + 1), char(i + 2)}); + } + + WriteBuffer("/data/test/ListFileCoreTest/text_1.txt"); + }; + static void TearDownTestCase() + { + rmdir(DIR_PATH); + rmdir(EMPTY_PATH); + }; + void SetUp() {}; + void TearDown() {}; +}; + +/** +* @tc.name: DoListFileCoreTest_0001 +* @tc.desc: Test function of DoListFileCore() interface for error suffix. +* @tc.size: MEDIUM +* @tc.type: FUNC +* @tc.level Level 1 +* @tc.require: AR000IGDNF +*/ +HWTEST_F(ListFileCoreTest, DoListFileCoreTest_0001, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ListFileCoreTest-begin DoListFileCoreTest_0001"; + FsListFileOptions opt; + FsFileFilter filter; + std::vector suffixVector = {"txt"}; + std::optional> optionalSuffix = suffixVector; + filter.SetSuffix(optionalSuffix); + opt.filter = filter; + + auto result = ListFileCore::DoListFile(DIR_PATH, opt); + EXPECT_FALSE(result.IsSuccess()); + + auto err = result.GetError(); + EXPECT_EQ(err.GetErrNo(), 13900020); + + GTEST_LOG_(INFO) << "ListFileCoreTest-end DoListFileCoreTest_0001"; +} + +/** +* @tc.name: DoListFileCoreTest_0002 +* @tc.desc: Test function of DoListFileCore() interface for error suffix. +* @tc.size: MEDIUM +* @tc.type: FUNC +* @tc.level Level 1 +* @tc.require: AR000IGDNF +*/ +HWTEST_F(ListFileCoreTest, DoListFileCoreTest_0002, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ListFileCoreTest-begin DoListFileCoreTest_0002"; + FsListFileOptions opt; + FsFileFilter filter; + std::vector suffixVector = {".tx@t"}; + std::optional> optionalSuffix = suffixVector; + filter.SetSuffix(optionalSuffix); + opt.filter = filter; + + auto result = ListFileCore::DoListFile(DIR_PATH, opt); + EXPECT_FALSE(result.IsSuccess()); + + auto err = result.GetError(); + EXPECT_EQ(err.GetErrNo(), 13900020); + + GTEST_LOG_(INFO) << "ListFileCoreTest-end DoListFileCoreTest_0002"; +} + +/** +* @tc.name: DoListFileCoreTest_0003 +* @tc.desc: Test function of DoListFileCore() interface for error listNum. +* @tc.size: MEDIUM +* @tc.type: FUNC +* @tc.level Level 1 +* @tc.require: AR000IGDNF +*/ +HWTEST_F(ListFileCoreTest, DoListFileCoreTest_0003, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ListFileCoreTest-begin DoListFileCoreTest_0003"; + FsListFileOptions opt; + opt.listNum = -5; + + auto result = ListFileCore::DoListFile(DIR_PATH, opt); + EXPECT_FALSE(result.IsSuccess()); + + auto err = result.GetError(); + EXPECT_EQ(err.GetErrNo(), 13900020); + + GTEST_LOG_(INFO) << "ListFileCoreTest-end DoListFileCoreTest_0003"; +} + +/** +* @tc.name: DoListFileCoreTest_0004 +* @tc.desc: Test function of DoListFileCore() interface for current suffix. +* @tc.size: MEDIUM +* @tc.type: FUNC +* @tc.level Level 1 +* @tc.require: AR000IGDNF +*/ +HWTEST_F(ListFileCoreTest, DoListFileCoreTest_0004, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ListFileCoreTest-begin DoListFileCoreTest_0004"; + FsListFileOptions opt; + FsFileFilter filter; + std::vector suffixVector = {".txt"}; + std::optional> optionalSuffix = suffixVector; + filter.SetSuffix(optionalSuffix); + opt.filter = filter; + + auto result = ListFileCore::DoListFile(DIR_PATH, opt); + ASSERT_TRUE(result.IsSuccess()); + + auto files = result.GetData().value(); + EXPECT_EQ(files.size(), 2); + EXPECT_EQ(files[0], "text_1.txt"); + + GTEST_LOG_(INFO) << "ListFileCoreTest-end DoListFileCoreTest_0004"; +} + +/** +* @tc.name: DoListFileCoreTest_0005 +* @tc.desc: Test function of DoListFileCore() interface for no maching suffix . +* @tc.size: MEDIUM +* @tc.type: FUNC +* @tc.level Level 1 +* @tc.require: AR000IGDNF +*/ +HWTEST_F(ListFileCoreTest, DoListFileCoreTest_0005, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ListFileCoreTest-begin DoListFileCoreTest_0005"; + FsListFileOptions opt; + FsFileFilter filter; + std::vector suffixVector = {".abc"}; + std::optional> optionalSuffix = suffixVector; + filter.SetSuffix(optionalSuffix); + opt.filter = filter; + + auto result = ListFileCore::DoListFile(DIR_PATH, opt); + ASSERT_TRUE(result.IsSuccess()); + + auto files = result.GetData().value(); + EXPECT_FALSE(files[0].empty()); + EXPECT_EQ(files[0], "level1"); + + GTEST_LOG_(INFO) << "ListFileCoreTest-end DoListFileCoreTest_0005"; +} + +/** +* @tc.name: DoListFileCoreTest_0006 +* @tc.desc: Test function of DoListFileCore() interface for current display name . +* @tc.size: MEDIUM +* @tc.type: FUNC +* @tc.level Level 1 +* @tc.require: AR000IGDNF +*/ +HWTEST_F(ListFileCoreTest, DoListFileCoreTest_0006, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ListFileCoreTest-begin DoListFileCoreTest_0006"; + FsListFileOptions opt; + FsFileFilter filter; + std::vector displayNameVector = {"text*.txt"}; + std::optional> optionalDisplayName = displayNameVector; + filter.SetDisplayName(optionalDisplayName); + opt.filter = filter; + + auto result = ListFileCore::DoListFile(DIR_PATH, opt); + ASSERT_TRUE(result.IsSuccess()); + + auto files = result.GetData().value(); + EXPECT_EQ(files.size(), 1); + EXPECT_EQ(files[0], "text_1.txt"); + + GTEST_LOG_(INFO) << "ListFileCoreTest-end DoListFileCoreTest_0006"; +} + +/** +* @tc.name: DoListFileCoreTest_0007 +* @tc.desc: Test function of DoListFileCore() interface for current fileSizeOver . +* @tc.size: MEDIUM +* @tc.type: FUNC +* @tc.level Level 1 +* @tc.require: AR000IGDNF +*/ +HWTEST_F(ListFileCoreTest, DoListFileCoreTest_0007, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ListFileCoreTest-begin DoListFileCoreTest_0007"; + FsListFileOptions opt; + FsFileFilter filter; + filter.SetFileSizeOver(500); + opt.filter = filter; + + auto result = ListFileCore::DoListFile(DIR_PATH, opt); + ASSERT_TRUE(result.IsSuccess()); + + auto files = result.GetData().value(); + EXPECT_EQ(files.size(), 2); + EXPECT_EQ(files[0], "text_1.txt"); + EXPECT_EQ(files[1], "level1"); + + GTEST_LOG_(INFO) << "ListFileCoreTest-end DoListFileCoreTest_0007"; +} + +/** +* @tc.name: DoListFileCoreTest_0008 +* @tc.desc: Test function of DoListFileCore() interface for displayMame = 0 . +* @tc.size: MEDIUM +* @tc.type: FUNC +* @tc.level Level 1 +* @tc.require: AR000IGDNF +*/ +HWTEST_F(ListFileCoreTest, DoListFileCoreTest_0008, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ListFileCoreTest-begin DoListFileCoreTest_0008"; + FsListFileOptions opt; + FsFileFilter filter; + std::vector displayNameVector = {}; + std::optional> optionalDisplayName = displayNameVector; + filter.SetDisplayName(optionalDisplayName); + opt.filter = filter; + + auto result = ListFileCore::DoListFile(DIR_PATH, opt); + EXPECT_FALSE(result.IsSuccess()); + + auto err = result.GetError(); + EXPECT_EQ(err.GetErrNo(), 13900020); + + GTEST_LOG_(INFO) << "ListFileCoreTest-end DoListFileCoreTest_0008"; +} + +/** +* @tc.name: DoListFileCoreTest_0009 +* @tc.desc: Test function of DoListFileCore() interface for error fileSizeOver . +* @tc.size: MEDIUM +* @tc.type: FUNC +* @tc.level Level 1 +* @tc.require: AR000IGDNF +*/ +HWTEST_F(ListFileCoreTest, DoListFileCoreTest_0009, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ListFileCoreTest-begin DoListFileCoreTest_0009"; + FsListFileOptions opt; + FsFileFilter filter; + filter.SetFileSizeOver(-1); + opt.filter = filter; + + auto result = ListFileCore::DoListFile(DIR_PATH, opt); + EXPECT_FALSE(result.IsSuccess()); + + auto err = result.GetError(); + EXPECT_EQ(err.GetErrNo(), 13900020); + + GTEST_LOG_(INFO) << "ListFileCoreTest-end DoListFileCoreTest_0009"; +} + +/** +* @tc.name: DoListFileCoreTest_0010 +* @tc.desc: Test function of DoListFileCore() interface for error lstModitiedAfter . +* @tc.size: MEDIUM +* @tc.type: FUNC +* @tc.level Level 1 +* @tc.require: AR000IGDNF +*/ +HWTEST_F(ListFileCoreTest, DoListFileCoreTest_0010, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ListFileCoreTest-begin DoListFileCoreTest_0010"; + FsListFileOptions opt; + FsFileFilter filter; + filter.SetLastModifiedAfter(-1); + opt.filter = filter; + + auto result = ListFileCore::DoListFile(DIR_PATH, opt); + EXPECT_FALSE(result.IsSuccess()); + + auto err = result.GetError(); + EXPECT_EQ(err.GetErrNo(), 13900020); + + GTEST_LOG_(INFO) << "ListFileCoreTest-end DoListFileCoreTest_0010"; +} + +/** +* @tc.name: DoListFileCoreTest_0011 +* @tc.desc: Test function of DoListFileCore() interface for true recursion . +* @tc.size: MEDIUM +* @tc.type: FUNC +* @tc.level Level 1 +* @tc.require: AR000IGDNF +*/ +HWTEST_F(ListFileCoreTest, DoListFileCoreTest_0011, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ListFileCoreTest-begin DoListFileCoreTest_0011"; + FsListFileOptions opt; + opt.recursion = true; + + auto result = ListFileCore::DoListFile(DIR_PATH, opt); + ASSERT_TRUE(result.IsSuccess()); + + auto files = result.GetData().value(); + EXPECT_EQ(files.size(), 12); + EXPECT_EQ(files[0], "/text_1.txt"); + + GTEST_LOG_(INFO) << "ListFileCoreTest-end DoListFileCoreTest_0011"; +} + +/** +* @tc.name: DoListFileCoreTest_0012 +* @tc.desc: Test function of DoListFileCore() interface for empty directory . +* @tc.size: MEDIUM +* @tc.type: FUNC +* @tc.level Level 1 +* @tc.require: AR000IGDNF +*/ +HWTEST_F(ListFileCoreTest, DoListFileCoreTest_0012, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ListFileCoreTest-begin DoListFileCoreTest_0012"; + auto result = ListFileCore::DoListFile(EMPTY_PATH); + ASSERT_TRUE(result.IsSuccess()); + + auto files = result.GetData().value(); + EXPECT_TRUE(files.empty()); + + GTEST_LOG_(INFO) << "ListFileCoreTest-end DoListFileCoreTest_0012"; +} + +/** +* @tc.name: DoListFileCoreTest_0013 +* @tc.desc: Test function of DoListFileCore() interface for current listNum. +* @tc.size: MEDIUM +* @tc.type: FUNC +* @tc.level Level 1 +* @tc.require: AR000IGDNF +*/ +HWTEST_F(ListFileCoreTest, DoListFileCoreTest_0013, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ListFileCoreTest-begin DoListFileCoreTest_0013"; + FsListFileOptions opt; + opt.listNum = 3; + + auto result = ListFileCore::DoListFile(DIR_PATH, opt); + ASSERT_TRUE(result.IsSuccess()); + + auto files = result.GetData().value(); + EXPECT_EQ(files.size(), 3); + + GTEST_LOG_(INFO) << "ListFileCoreTest-end DoListFileCoreTest_0013"; +} + +/** +* @tc.name: DoListFileCoreTest_0014 +* @tc.desc: Test function of DoListFileCore() interface for no such file or directory. +* @tc.size: MEDIUM +* @tc.type: FUNC +* @tc.level Level 1 +* @tc.require: AR000IGDNF +*/ +HWTEST_F(ListFileCoreTest, DoListFileCoreTest_0014, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ListFileCoreTest-begin DoListFileCoreTest_0014"; + auto result = ListFileCore::DoListFile("/data/local/tmp/ascecedssw"); + EXPECT_FALSE(result.IsSuccess()); + + auto err = result.GetError(); + EXPECT_EQ(err.GetErrNo(), 13900002); + + GTEST_LOG_(INFO) << "ListFileCoreTest-end DoListFileCoreTest_0014"; +} + +/** +* @tc.name: DoListFileCoreTest_0015 +* @tc.desc: Test function of DoListFileCore() interface for >256 length suffix. +* @tc.size: MEDIUM +* @tc.type: FUNC +* @tc.level Level 1 +* @tc.require: AR000IGDNF +*/ +HWTEST_F(ListFileCoreTest, DoListFileCoreTest_0015, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ListFileCoreTest-begin DoListFileCoreTest_0015"; + FsListFileOptions opt; + FsFileFilter filter; + + const size_t targetLength = 257; + std::string str = "."; + for (size_t i = 1; i < targetLength; ++i) { + str += std::to_string(i % 10); + } + + std::vector suffixVector = {str}; + std::optional> optionalSuffix = suffixVector; + filter.SetSuffix(optionalSuffix); + opt.filter = filter; + + auto result = ListFileCore::DoListFile(DIR_PATH, opt); + EXPECT_FALSE(result.IsSuccess()); + + auto err = result.GetError(); + EXPECT_EQ(err.GetErrNo(), 13900020); + + GTEST_LOG_(INFO) << "ListFileCoreTest-end DoListFileCoreTest_0015"; +} + +/** +* @tc.name: DoListFileCoreTest_0016 +* @tc.desc: Test function of DoListFileCore() interface for empty suffix. +* @tc.size: MEDIUM +* @tc.type: FUNC +* @tc.level Level 1 +* @tc.require: AR000IGDNF +*/ +HWTEST_F(ListFileCoreTest, DoListFileCoreTest_0016, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ListFileCoreTest-begin DoListFileCoreTest_0016"; + FsListFileOptions opt; + FsFileFilter filter; + std::vector suffixVector = {}; + std::optional> optionalSuffix = suffixVector; + filter.SetSuffix(optionalSuffix); + opt.filter = filter; + + auto result = ListFileCore::DoListFile(DIR_PATH, opt); + EXPECT_FALSE(result.IsSuccess()); + + auto err = result.GetError(); + EXPECT_EQ(err.GetErrNo(), 13900020); + + GTEST_LOG_(INFO) << "ListFileCoreTest-end DoListFileCoreTest_0016"; +} + +/** +* @tc.name: DoListFileCoreTest_0017 +* @tc.desc: Test function of DoListFileCore() interface for 0 listNum. +* @tc.size: MEDIUM +* @tc.type: FUNC +* @tc.level Level 1 +* @tc.require: AR000IGDNF +*/ +HWTEST_F(ListFileCoreTest, DoListFileCoreTest_0017, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ListFileCoreTest-begin DoListFileCoreTest_0017"; + FsListFileOptions opt; + opt.listNum = 0; + + auto result = ListFileCore::DoListFile(DIR_PATH, opt); + ASSERT_TRUE(result.IsSuccess()); + + auto files = result.GetData().value(); + EXPECT_EQ(files.size(), 5); + + GTEST_LOG_(INFO) << "ListFileCoreTest-end DoListFileCoreTest_0017"; +} + +} +} +} \ No newline at end of file diff --git a/interfaces/test/unittest/js/mod_fs/properties/mkdir_core_mock_test.cpp b/interfaces/test/unittest/js/mod_fs/properties/mkdir_core_mock_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..34c0d40b50f042e93ad92e7d49a34670ed9e9ff8 --- /dev/null +++ b/interfaces/test/unittest/js/mod_fs/properties/mkdir_core_mock_test.cpp @@ -0,0 +1,183 @@ +/* + * Copyright (C) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include +#include + +#include "mkdir_core.h" +#include "mock/uv_fs_mock.h" + +namespace OHOS::FileManagement::ModuleFileIO::Test { +using namespace testing; +using namespace testing::ext; +using namespace std; + +class MkdirCoreMockTest : public testing::Test { +public: + static filesystem::path tempFilePath; + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); + static inline shared_ptr uvMock = nullptr; +}; + +filesystem::path MkdirCoreMockTest::tempFilePath; + +void MkdirCoreMockTest::SetUpTestCase(void) +{ + GTEST_LOG_(INFO) << "SetUpTestCase"; + tempFilePath = filesystem::temp_directory_path() / "test"; + std::filesystem::create_directory(tempFilePath); + uvMock = std::make_shared(); + Uvfs::ins = uvMock; +} + +void MkdirCoreMockTest::TearDownTestCase(void) +{ + GTEST_LOG_(INFO) << "TearDownTestCase"; + filesystem::remove_all(tempFilePath); + Uvfs::ins = nullptr; + uvMock = nullptr; +} + +void MkdirCoreMockTest::SetUp(void) +{ + GTEST_LOG_(INFO) << "SetUp"; +} + +void MkdirCoreMockTest::TearDown(void) +{ + GTEST_LOG_(INFO) << "TearDown"; +} + +/** + * @tc.name: MkdirCoreMockTest_DoMkdir_0001 + * @tc.desc: Test function of DoMkdir() interface for SUCCESS. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: AR000IGDNF + */ +HWTEST_F(MkdirCoreMockTest, MkdirCoreMockTest_DoMkdir_0001, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "MkdirCoreMockTest-begin MkdirCoreMockTest_DoMkdir_0001"; + + EXPECT_CALL(*uvMock, uv_fs_mkdir(_, _, _, _, _)).WillOnce(Return(0)); + + string path = tempFilePath.string() + "/test01"; + auto ret = MkdirCore::DoMkdir(path); + EXPECT_EQ(ret.IsSuccess(), true); + + GTEST_LOG_(INFO) << "MkdirCoreMockTest-end MkdirCoreMockTest_DoMkdir_0001"; +} + +/** + * @tc.name: MkdirCoreMockTest_DoMkdir_0002 + * @tc.desc: Test function of DoMkdir() interface for SUCCESS. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: AR000IGDNF + */ +HWTEST_F(MkdirCoreMockTest, MkdirCoreMockTest_DoMkdir_0002, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "MkdirCoreMockTest-begin MkdirCoreMockTest_DoMkdir_0002"; + + EXPECT_CALL(*uvMock, uv_fs_access(_, _, _, _, _)).WillOnce(Return(-2)).WillOnce(Return(0)); + + string path = tempFilePath.string() + "/test02/testDir"; + auto ret = MkdirCore::DoMkdir(path, true); + EXPECT_EQ(ret.IsSuccess(), true); + + GTEST_LOG_(INFO) << "MkdirCoreMockTest-end MkdirCoreMockTest_DoMkdir_0002"; +} + +/** + * @tc.name: MkdirCoreMockTest_DoMkdir_0003 + * @tc.desc: Test function of DoMkdir() interface for FAILED. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: AR000IGDNF + */ +HWTEST_F(MkdirCoreMockTest, MkdirCoreMockTest_DoMkdir_0003, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "MkdirCoreMockTest-begin MkdirCoreMockTest_DoMkdir_0003"; + + EXPECT_CALL(*uvMock, uv_fs_mkdir(_, _, _, _, _)).WillOnce(Return(1)); + + string path = tempFilePath.string() + "/test03"; + auto ret = MkdirCore::DoMkdir(path); + EXPECT_EQ(ret.IsSuccess(), false); + + GTEST_LOG_(INFO) << "MkdirCoreMockTest-end MkdirCoreMockTest_DoMkdir_0003"; +} + +/** + * @tc.name: MkdirCoreMockTest_DoMkdir_0004 + * @tc.desc: Test function of DoMkdir() interface for FAILED. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: AR000IGDNF + */ +HWTEST_F(MkdirCoreMockTest, MkdirCoreMockTest_DoMkdir_0004, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "MkdirCoreMockTest-begin MkdirCoreMockTest_DoMkdir_0004"; + + EXPECT_CALL(*uvMock, uv_fs_access(_, _, _, _, _)).WillOnce(Return(0)); + + string path = "/"; + auto ret = MkdirCore::DoMkdir(path, true); + EXPECT_EQ(ret.IsSuccess(), false); + auto err = ret.GetError(); + int errCode = err.GetErrNo(); + EXPECT_EQ(errCode, 13900015); + auto msg = err.GetErrMsg(); + EXPECT_EQ(msg, "File exists"); + + GTEST_LOG_(INFO) << "MkdirCoreMockTest-end MkdirCoreMockTest_DoMkdir_0004"; +} + +/** + * @tc.name: MkdirCoreMockTest_DoMkdir_0005 + * @tc.desc: Test function of DoMkdir() interface for FAILED. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: AR000IGDNF + */ +HWTEST_F(MkdirCoreMockTest, MkdirCoreMockTest_DoMkdir_0005, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "MkdirCoreMockTest-begin MkdirCoreMockTest_DoMkdir_0005"; + + EXPECT_CALL(*uvMock, uv_fs_access(_, _, _, _, _)).WillOnce(Return(2)); + + string path = ""; + auto ret = MkdirCore::DoMkdir(path, true); + EXPECT_EQ(ret.IsSuccess(), false); + auto err = ret.GetError(); + int errCode = err.GetErrNo(); + EXPECT_EQ(errCode, 13900002); + auto msg = err.GetErrMsg(); + EXPECT_EQ(msg, "No such file or directory"); + + GTEST_LOG_(INFO) << "MkdirCoreMockTest-end MkdirCoreMockTest_DoMkdir_0005"; +} + +} // namespace OHOS::FileManagement::ModuleFileIO::Test \ No newline at end of file diff --git a/interfaces/test/unittest/js/mod_fs/properties/mock/system_mock.cpp b/interfaces/test/unittest/js/mod_fs/properties/mock/system_mock.cpp new file mode 100644 index 0000000000000000000000000000000000000000..5878a93046576b034577b1d1431decb895cdb2dc --- /dev/null +++ b/interfaces/test/unittest/js/mod_fs/properties/mock/system_mock.cpp @@ -0,0 +1,40 @@ +/* + * Copyright (C) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "system_mock.h" + +using namespace OHOS::FileManagement::ModuleFileIO; + +extern "C" { +int setxattr(const char *path, const char *name, const void *value, size_t size, int flags) +{ + return System::ins->setxattr(path, name, value, size, flags); +} + +int getxattr(const char *path, const char *name, void *value, size_t size) +{ + return System::ins->getxattr(path, name, value, size); +} + +int fgetxattr(int filedes, const char *name, void *value, size_t size) +{ + return System::ins->fgetxattr(filedes, name, value, size); +} + +int flock(int fd, int operation) +{ + return System::ins->flock(fd, operation); +} +} \ No newline at end of file diff --git a/interfaces/test/unittest/js/mod_fs/properties/mock/system_mock.h b/interfaces/test/unittest/js/mod_fs/properties/mock/system_mock.h new file mode 100644 index 0000000000000000000000000000000000000000..3ff74be78027d70a93550e1fbb0a4d59a0331885 --- /dev/null +++ b/interfaces/test/unittest/js/mod_fs/properties/mock/system_mock.h @@ -0,0 +1,46 @@ +/* + * Copyright (C) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef INTERFACES_TEST_UNITTEST_JS_MOD_FS_PROPERTIES_MOCK_SYSTEM_MOCK_H +#define INTERFACES_TEST_UNITTEST_JS_MOD_FS_PROPERTIES_MOCK_SYSTEM_MOCK_H + +#include +#include +#include + +namespace OHOS::FileManagement::ModuleFileIO { + +class System { +public: + static inline std::shared_ptr ins = nullptr; + +public: + virtual ~System() = default; + virtual int setxattr(const char *path, const char *name, const void *value, size_t size, int flags) = 0; + virtual int getxattr(const char *path, const char *name, void *value, size_t size) = 0; + virtual int fgetxattr(int filedes, const char *name, void *value, size_t size) = 0; + virtual int flock(int fd, int operation) = 0; +}; + +class SystemMock : public System { +public: + MOCK_METHOD5(setxattr, int(const char *path, const char *name, const void *value, size_t size, int flags)); + MOCK_METHOD4(getxattr, int(const char *path, const char *name, void *value, size_t size)); + MOCK_METHOD4(fgetxattr, int(int filedes, const char *name, void *value, size_t size)); + MOCK_METHOD2(flock, int(int fd, int operation)); +}; + +} // namespace OHOS::FileManagement::ModuleFileIO +#endif // INTERFACES_TEST_UNITTEST_JS_MOD_FS_PROPERTIES_MOCK_SYSTEM_MOCK_H \ No newline at end of file diff --git a/interfaces/test/unittest/js/mod_fs/properties/mock/uv_fs_mock.cpp b/interfaces/test/unittest/js/mod_fs/properties/mock/uv_fs_mock.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b656a1ad103d4e47cc0346e49b7d1fc1e074035c --- /dev/null +++ b/interfaces/test/unittest/js/mod_fs/properties/mock/uv_fs_mock.cpp @@ -0,0 +1,137 @@ +/* + * Copyright (C) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#include "uv_fs_mock.h" + + +using namespace OHOS::FileManagement::ModuleFileIO; + +int uv_fs_read(uv_loop_t *loop, uv_fs_t *req, uv_file file, const uv_buf_t bufs[], unsigned int nbufs, int64_t off, + uv_fs_cb cb) +{ + return Uvfs::ins->uv_fs_read(loop, req, file, bufs, nbufs, off, cb); +} + +int uv_fs_readlink(uv_loop_t *loop, uv_fs_t *req, const char *path, uv_fs_cb cb) +{ + return Uvfs::ins->uv_fs_readlink(loop, req, path, cb); +} + +int uv_fs_stat(uv_loop_t *loop, uv_fs_t *req, const char *path, uv_fs_cb cb) +{ + return Uvfs::ins->uv_fs_stat(loop, req, path, cb); +} + +int uv_fs_utime(uv_loop_t *loop, uv_fs_t *req, const char *path, double atime, double mtime, uv_fs_cb cb) +{ + return Uvfs::ins->uv_fs_utime(loop, req, path, atime, mtime, cb); +} + +int uv_fs_scandir(uv_loop_t *loop, uv_fs_t *req, const char *path, int flags, uv_fs_cb cb) +{ + return Uvfs::ins->uv_fs_scandir(loop, req, path, flags, cb); +} + +int uv_fs_scandir_next(uv_fs_t *req, uv_dirent_t *ent) +{ + return Uvfs::ins->uv_fs_scandir_next(req, ent); +} + +int uv_fs_rmdir(uv_loop_t *loop, uv_fs_t *req, const char *path, uv_fs_cb cb) +{ + return Uvfs::ins->uv_fs_rmdir(loop, req, path, cb); +} + +int uv_fs_symlink(uv_loop_t *loop, uv_fs_t *req, const char *path, const char *new_path, int flags, uv_fs_cb cb) +{ + return Uvfs::ins->uv_fs_symlink(loop, req, path, new_path, flags, cb); +} + +int uv_fs_open(uv_loop_t *loop, uv_fs_t *req, const char *path, int flags, int mode, uv_fs_cb cb) +{ + return Uvfs::ins->uv_fs_open(loop, req, path, flags, mode, cb); +} + +int uv_fs_ftruncate(uv_loop_t *loop, uv_fs_t *req, uv_file fd, int64_t offset, uv_fs_cb cb) +{ + return Uvfs::ins->uv_fs_ftruncate(loop, req, fd, offset, cb); +} + +int uv_fs_write(uv_loop_t *loop, uv_fs_t *req, uv_file fd, const uv_buf_t bufs[], unsigned int nbufs, int64_t offset, + uv_fs_cb cb) +{ + return Uvfs::ins->uv_fs_write(loop, req, fd, bufs, nbufs, offset, cb); +} + +int uv_fs_realpath(uv_loop_t *loop, uv_fs_t *req, const char *path, uv_fs_cb cb) +{ + return Uvfs::ins->uv_fs_realpath(loop, req, path, cb); +} + +int uv_fs_close(uv_loop_t *loop, uv_fs_t *req, uv_file file, uv_fs_cb cb) +{ + return Uvfs::ins->uv_fs_close(loop, req, file, cb); +} + +int uv_fs_fdatasync(uv_loop_t *loop, uv_fs_t *req, uv_file file, uv_fs_cb cb) +{ + return Uvfs::ins->uv_fs_fdatasync(loop, req, file, cb); +} + +int uv_fs_mkdir(uv_loop_t *loop, uv_fs_t *req, const char *path, int mode, uv_fs_cb cb) +{ + return Uvfs::ins->uv_fs_mkdir(loop, req, path, mode, cb); +} + +int uv_fs_access(uv_loop_t *loop, uv_fs_t *req, const char *path, int flags, uv_fs_cb cb) +{ + return Uvfs::ins->uv_fs_access(loop, req, path, flags, cb); +} + +int uv_fs_mkdtemp(uv_loop_t *loop, uv_fs_t *req, const char *tpl, uv_fs_cb cb) +{ + return Uvfs::ins->uv_fs_mkdtemp(loop, req, tpl, cb); +} + +int uv_fs_unlink(uv_loop_t *loop, uv_fs_t *req, const char *path, uv_fs_cb cb) +{ + return Uvfs::ins->uv_fs_unlink(loop, req, path, cb); +} + +void uv_fs_req_cleanup(uv_fs_t *req) +{ + return; +} + +int uv_fs_rename(uv_loop_t *loop, uv_fs_t *req, const char *path, const char *newPath, uv_fs_cb cb) +{ + return Uvfs::ins->uv_fs_rename(loop, req, path, newPath, cb); +} + +int uv_fs_fsync(uv_loop_t *loop, uv_fs_t *req, uv_file file, uv_fs_cb cb) +{ + return Uvfs::ins->uv_fs_fsync(loop, req, file, cb); +} + +int uv_fs_sendfile(uv_loop_t *loop, uv_fs_t *req, uv_file outFd, uv_file inFd, int64_t off, size_t len, uv_fs_cb cb) +{ + return Uvfs::ins->uv_fs_sendfile(loop, req, outFd, inFd, off, len, cb); +} + +int uv_fs_lstat(uv_loop_t *loop, uv_fs_t *req, const char *path, uv_fs_cb cb) +{ + return Uvfs::ins->uv_fs_lstat(loop, req, path, cb); +} \ No newline at end of file diff --git a/interfaces/test/unittest/js/mod_fs/properties/mock/uv_fs_mock.h b/interfaces/test/unittest/js/mod_fs/properties/mock/uv_fs_mock.h new file mode 100644 index 0000000000000000000000000000000000000000..1fa703a0fe7ba997c03ec58c580c35c2220b40a8 --- /dev/null +++ b/interfaces/test/unittest/js/mod_fs/properties/mock/uv_fs_mock.h @@ -0,0 +1,91 @@ +/* + * Copyright (C) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef UV_FS_READ_MOCK_H +#define UV_FS_READ_MOCK_H + +#include "uv.h" + +#include + +namespace OHOS::FileManagement::ModuleFileIO { + +class Uvfs { +public: + static inline std::shared_ptr ins = nullptr; +public: + virtual ~Uvfs() = default; + virtual int uv_fs_read(uv_loop_t *loop, uv_fs_t *req, uv_file file, const uv_buf_t bufs[], unsigned int nbufs, + int64_t off, uv_fs_cb cb) = 0; + virtual int uv_fs_readlink(uv_loop_t *loop, uv_fs_t *req, const char *path, uv_fs_cb cb) = 0; + virtual int uv_fs_stat(uv_loop_t *loop, uv_fs_t *req, const char *path, uv_fs_cb cb) = 0; + virtual int uv_fs_utime(uv_loop_t *loop, uv_fs_t *req, const char *path, double atime, + double mtime, uv_fs_cb cb) = 0; + virtual int uv_fs_scandir(uv_loop_t *loop, uv_fs_t *req, const char *path, int flags, uv_fs_cb cb) = 0; + virtual int uv_fs_scandir_next(uv_fs_t *req, uv_dirent_t *ent) = 0; + virtual int uv_fs_rmdir(uv_loop_t *loop, uv_fs_t *req, const char* path, uv_fs_cb cb) = 0; + virtual int uv_fs_symlink(uv_loop_t *loop, uv_fs_t *req, const char *path, const char *new_path, int flags, + uv_fs_cb cb) = 0; + virtual int uv_fs_open(uv_loop_t *loop, uv_fs_t *req, const char *path, int flags, int mode, uv_fs_cb cb) = 0; + virtual int uv_fs_ftruncate(uv_loop_t *loop, uv_fs_t *req, uv_file fd, int64_t offset, uv_fs_cb cb) = 0; + virtual int uv_fs_write(uv_loop_t *loop, uv_fs_t *req, uv_file fd, const uv_buf_t bufs[], unsigned int nbufs, + int64_t offset, uv_fs_cb cb) = 0; + virtual int uv_fs_realpath(uv_loop_t *loop, uv_fs_t *req, const char *path, uv_fs_cb cb) = 0; + virtual int uv_fs_close(uv_loop_t *loop, uv_fs_t *req, uv_file file, uv_fs_cb cb) = 0; + virtual int uv_fs_fdatasync(uv_loop_t *loop, uv_fs_t *req, uv_file file, uv_fs_cb cb) = 0; + virtual int uv_fs_mkdir(uv_loop_t *loop, uv_fs_t *req, const char *path, int mode, uv_fs_cb cb) = 0; + virtual int uv_fs_access(uv_loop_t *loop, uv_fs_t *req, const char *path, int flags, uv_fs_cb cb) = 0; + virtual int uv_fs_mkdtemp(uv_loop_t *loop, uv_fs_t *req, const char *tpl, uv_fs_cb cb) = 0; + virtual int uv_fs_unlink(uv_loop_t *loop, uv_fs_t *req, const char *path, uv_fs_cb cb) = 0; + virtual int uv_fs_rename(uv_loop_t *loop, uv_fs_t *req, const char *path, const char *newPath, uv_fs_cb cb) = 0; + virtual int uv_fs_fsync(uv_loop_t* loop, uv_fs_t* req, uv_file file, uv_fs_cb cb) = 0; + virtual int uv_fs_sendfile(uv_loop_t* loop, uv_fs_t* req, uv_file outFd, uv_file inFd, + int64_t off, size_t len, uv_fs_cb cb) = 0; + virtual int uv_fs_lstat(uv_loop_t *loop, uv_fs_t *req, const char *path, uv_fs_cb cb) = 0; +}; + +class UvfsMock : public Uvfs { +public: + MOCK_METHOD7(uv_fs_read, int(uv_loop_t *loop, uv_fs_t *req, uv_file file, const uv_buf_t bufs[], unsigned int nbufs, + int64_t off, uv_fs_cb cb)); + MOCK_METHOD4(uv_fs_readlink, int(uv_loop_t *loop, uv_fs_t *req, const char *path, uv_fs_cb cb)); + MOCK_METHOD4(uv_fs_stat, int(uv_loop_t *loop, uv_fs_t *req, const char *path, uv_fs_cb cb)); + MOCK_METHOD6(uv_fs_utime, int(uv_loop_t *loop, uv_fs_t *req, const char *path, double atime, double mtime, + uv_fs_cb cb)); + MOCK_METHOD5(uv_fs_scandir, int(uv_loop_t *loop, uv_fs_t *req, const char *path, int flags, uv_fs_cb cb)); + MOCK_METHOD2(uv_fs_scandir_next, int(uv_fs_t *req, uv_dirent_t *ent)); + MOCK_METHOD4(uv_fs_rmdir, int(uv_loop_t *loop, uv_fs_t *req, const char *path, uv_fs_cb cb)); + MOCK_METHOD6(uv_fs_symlink, int(uv_loop_t *loop, uv_fs_t *req, const char *path, const char *new_path, int flags, + uv_fs_cb cb)); + MOCK_METHOD6(uv_fs_open, int(uv_loop_t *loop, uv_fs_t *req, const char *path, int flags, int mode, uv_fs_cb cb)); + MOCK_METHOD5(uv_fs_ftruncate, int(uv_loop_t *loop, uv_fs_t *req, uv_file fd, int64_t offset, uv_fs_cb cb)); + MOCK_METHOD7(uv_fs_write, int(uv_loop_t *loop, uv_fs_t *req, uv_file fd, const uv_buf_t bufs[], unsigned int nbufs, + int64_t offset, uv_fs_cb cb)); + MOCK_METHOD4(uv_fs_realpath, int(uv_loop_t *loop, uv_fs_t *req, const char *path, uv_fs_cb cb)); + MOCK_METHOD4(uv_fs_close, int(uv_loop_t *loop, uv_fs_t *req, uv_file file, uv_fs_cb cb)); + MOCK_METHOD4(uv_fs_fdatasync, int(uv_loop_t *loop, uv_fs_t *req, uv_file file, uv_fs_cb cb)); + MOCK_METHOD5(uv_fs_mkdir, int(uv_loop_t *loop, uv_fs_t *req, const char *path, int mode, uv_fs_cb cb)); + MOCK_METHOD5(uv_fs_access, int(uv_loop_t *loop, uv_fs_t *req, const char *path, int flags, uv_fs_cb cb)); + MOCK_METHOD4(uv_fs_mkdtemp, int(uv_loop_t *loop, uv_fs_t *req, const char *tpl, uv_fs_cb cb)); + MOCK_METHOD4(uv_fs_unlink, int(uv_loop_t *loop, uv_fs_t *req, const char *path, uv_fs_cb cb)); + MOCK_METHOD5(uv_fs_rename, int(uv_loop_t *loop, uv_fs_t *req, const char *path, const char *newPath, uv_fs_cb cb)); + MOCK_METHOD4(uv_fs_fsync, int(uv_loop_t* loop, uv_fs_t* req, uv_file file, uv_fs_cb cb)); + MOCK_METHOD7(uv_fs_sendfile, int(uv_loop_t* loop, uv_fs_t* req, uv_file outFd, uv_file inFd, + int64_t off, size_t len, uv_fs_cb cb)); + MOCK_METHOD4(uv_fs_lstat, int(uv_loop_t *loop, uv_fs_t *req, const char *path, uv_fs_cb cb)); +}; + +} // OHOS::FileManagement::ModuleFileIO +#endif \ No newline at end of file diff --git a/interfaces/test/unittest/js/mod_fs/properties/move_core_mock_test.cpp b/interfaces/test/unittest/js/mod_fs/properties/move_core_mock_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..175fd3ab1324a9614761f3d8b7d78da053a84c01 --- /dev/null +++ b/interfaces/test/unittest/js/mod_fs/properties/move_core_mock_test.cpp @@ -0,0 +1,450 @@ +/* + * Copyright (C) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "move_core.h" +#include "uv_fs_mock.h" + +#include + +namespace OHOS::FileManagement::ModuleFileIO::Test { +using namespace testing; +using namespace testing::ext; +using namespace std; + +class MoveCoreMockTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); + static inline std::shared_ptr uvMock = nullptr; +}; + +void MoveCoreMockTest::SetUpTestCase(void) +{ + GTEST_LOG_(INFO) << "SetUpTestCase"; + uvMock = std::make_shared(); + Uvfs::ins = uvMock; +} + +void MoveCoreMockTest::TearDownTestCase(void) +{ + GTEST_LOG_(INFO) << "TearDownTestCase"; + Uvfs::ins = nullptr; + uvMock = nullptr; +} + +void MoveCoreMockTest::SetUp(void) +{ + GTEST_LOG_(INFO) << "SetUp"; +} + +void MoveCoreMockTest::TearDown(void) +{ + GTEST_LOG_(INFO) << "TearDown"; +} + +extern "C" { + const char* uv_err_name(int err) + { + return "EXDEV"; + } +} + +/** + * @tc.name: MoveCoreMockTest_DoMove_000 + * @tc.desc: Test function of MoveCore::DoMove interface for SUCCESS. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(MoveCoreMockTest, MoveCoreMockTest_DoMove_000, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "MoveCoreMockTest-begin MoveCoreMockTest_DoMove_000"; + + std::string src; + std::string dest; + + EXPECT_CALL(*uvMock, uv_fs_access(_, _, _, _, _)).WillOnce(Return(0)); + EXPECT_CALL(*uvMock, uv_fs_rename(_, _, _, _, _)).WillOnce(Return(0)); + + auto res = MoveCore::DoMove(src, dest); + EXPECT_EQ(res.IsSuccess(), true); + + GTEST_LOG_(INFO) << "MoveCoreMockTest-end MoveCoreMockTest_DoMove_000"; +} + +/** + * @tc.name: MoveCoreMockTest_DoMove_001 + * @tc.desc: Test function of MoveCore::DoMove interface for FALSE. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(MoveCoreMockTest, MoveCoreMockTest_DoMove_001, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "MoveCoreMockTest-begin MoveCoreMockTest_DoMove_001"; + + std::string src; + std::string dest; + + EXPECT_CALL(*uvMock, uv_fs_access(_, _, _, _, _)).WillOnce(Return(0)); + EXPECT_CALL(*uvMock, uv_fs_rename(_, _, _, _, _)).WillOnce(Return(-1)); + + auto res = MoveCore::DoMove(src, dest); + EXPECT_EQ(res.IsSuccess(), false); + + GTEST_LOG_(INFO) << "MoveCoreMockTest-end MoveCoreMockTest_DoMove_001"; +} + +/** + * @tc.name: MoveCoreMockTest_DoMove_002 + * @tc.desc: Test function of MoveCore::DoMove interface for FAILED. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(MoveCoreMockTest, MoveCoreMockTest_DoMove_002, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "MoveCoreMockTest-begin MoveCoreMockTest_DoMove_002"; + + std::string src; + std::string dest; + optional mode = std::make_optional(MODE_FORCE_MOVE); + + EXPECT_CALL(*uvMock, uv_fs_access(_, _, _, _, _)).WillOnce(Return(0)); + EXPECT_CALL(*uvMock, uv_fs_rename(_, _, _, _, _)).WillOnce(Return(-1)); + + auto res = MoveCore::DoMove(src, dest, mode); + EXPECT_EQ(res.IsSuccess(), false); + GTEST_LOG_(INFO) << "MoveCoreMockTest-end MoveCoreMockTest_DoMove_002"; +} + +/** + * @tc.name: MoveCoreMockTest_DoMove_003 + * @tc.desc: Test function of MoveCore::DoMove interface for FALSE. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(MoveCoreMockTest, MoveCoreMockTest_DoMove_003, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "MoveCoreMockTest-begin MoveCoreMockTest_DoMove_003"; + + std::string src; + std::string dest; + + EXPECT_CALL(*uvMock, uv_fs_access(_, _, _, _, _)).WillOnce(Return(-1)); + + auto res = MoveCore::DoMove(src, dest); + EXPECT_EQ(res.IsSuccess(), false); + + GTEST_LOG_(INFO) << "MoveCoreMockTest-end MoveCoreMockTest_DoMove_003"; +} + +/** + * @tc.name: MoveCoreMockTest_DoMove_004 + * @tc.desc: Test function of MoveCore::DoMove interface for FALSE. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(MoveCoreMockTest, MoveCoreMockTest_DoMove_004, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "MoveCoreMockTest-begin MoveCoreMockTest_DoMove_004"; + + std::string src; + std::string dest; + optional mode = std::make_optional(MODE_THROW_ERR); + + EXPECT_CALL(*uvMock, uv_fs_access(_, _, _, _, _)).WillOnce(Return(1)).WillOnce(Return(0)); + + auto res = MoveCore::DoMove(src, dest, mode); + EXPECT_EQ(res.IsSuccess(), false); + + GTEST_LOG_(INFO) << "MoveCoreMockTest-end MoveCoreMockTest_DoMove_004"; +} + +/** + * @tc.name: MoveCoreMockTest_DoMove_005 + * @tc.desc: Test function of MoveCore::DoMove interface for FALSE. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(MoveCoreMockTest, MoveCoreMockTest_DoMove_005, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "MoveCoreMockTest-begin MoveCoreMockTest_DoMove_005"; + + std::string src; + std::string dest; + optional mode = std::make_optional(MODE_THROW_ERR); + + EXPECT_CALL(*uvMock, uv_fs_access(_, _, _, _, _)).WillOnce(Return(1)).WillOnce(Return(-1)); + + auto res = MoveCore::DoMove(src, dest, mode); + EXPECT_EQ(res.IsSuccess(), false); + + GTEST_LOG_(INFO) << "MoveCoreMockTest-end MoveCoreMockTest_DoMove_005"; +} + +/** + * @tc.name: MoveCoreMockTest_DoMove_006 + * @tc.desc: Test function of MoveCore::DoMove interface for FALSE. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(MoveCoreMockTest, MoveCoreMockTest_DoMove_006, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "MoveCoreMockTest-begin MoveCoreMockTest_DoMove_006"; + + std::string src; + std::string dest; + optional mode = std::make_optional(MODE_FORCE_MOVE); + + EXPECT_CALL(*uvMock, uv_fs_access(_, _, _, _, _)).WillOnce(Return(1)); + EXPECT_CALL(*uvMock, uv_fs_rename(_, _, _, _, _)).WillOnce(Return(-1)); + + auto res = MoveCore::DoMove(src, dest, mode); + EXPECT_EQ(res.IsSuccess(), false); + + GTEST_LOG_(INFO) << "MoveCoreMockTest-end MoveCoreMockTest_DoMove_006"; +} + +/** + * @tc.name: MoveCoreMockTest_DoMove_007 + * @tc.desc: Test function of MoveCore::DoMove interface for FALSE. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(MoveCoreMockTest, MoveCoreMockTest_DoMove_007, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "MoveCoreMockTest-begin MoveCoreMockTest_DoMove_007"; + + std::string src; + std::string dest; + optional mode = std::make_optional(MODE_FORCE_MOVE); + + EXPECT_CALL(*uvMock, uv_fs_access(_, _, _, _, _)).WillOnce(Return(1)); + EXPECT_CALL(*uvMock, uv_fs_rename(_, _, _, _, _)).WillOnce(Return(1)); + + auto res = MoveCore::DoMove(src, dest, mode); + EXPECT_EQ(res.IsSuccess(), true); + + GTEST_LOG_(INFO) << "MoveCoreMockTest-end MoveCoreMockTest_DoMove_007"; +} + +/** + * @tc.name: MoveCoreMockTest_DoMove_008 + * @tc.desc: Test function of MoveCore::DoMove interface for FALSE. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(MoveCoreMockTest, MoveCoreMockTest_DoMove_008, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "MoveCoreMockTest-begin MoveCoreMockTest_DoMove_008"; + + std::string src; + std::string dest; + + EXPECT_CALL(*uvMock, uv_fs_access(_, _, _, _, _)).WillOnce(Return(0)); + EXPECT_CALL(*uvMock, uv_fs_rename(_, _, _, _, _)).WillOnce(Return(1)); + + auto res = MoveCore::DoMove(src, dest); + EXPECT_EQ(res.IsSuccess(), true); + + GTEST_LOG_(INFO) << "MoveCoreMockTest-end MoveCoreMockTest_DoMove_008"; +} + +/** + * @tc.name: MoveCoreMockTest_DoMove_009 + * @tc.desc: Test function of MoveCore::DoMove interface for FALSE. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(MoveCoreMockTest, MoveCoreMockTest_DoMove_009, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "MoveCoreMockTest-begin MoveCoreMockTest_DoMove_009"; + + std::string src; + std::string dest; + optional mode = std::make_optional(MODE_FORCE_MOVE); + + EXPECT_CALL(*uvMock, uv_fs_access(_, _, _, _, _)).WillOnce(Return(1)); + EXPECT_CALL(*uvMock, uv_fs_rename(_, _, _, _, _)).WillOnce(Return(-1)); + EXPECT_CALL(*uvMock, uv_fs_stat(_, _, _, _)).WillOnce(Return(-1)); + + auto res = MoveCore::DoMove(src, dest, mode); + EXPECT_EQ(res.IsSuccess(), false); + + GTEST_LOG_(INFO) << "MoveCoreMockTest-end MoveCoreMockTest_DoMove_009"; +} + +/** + * @tc.name: MoveCoreMockTest_DoMove_0010 + * @tc.desc: Test function of MoveCore::DoMove interface for FALSE. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(MoveCoreMockTest, MoveCoreMockTest_DoMove_0010, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "MoveCoreMockTest-begin MoveCoreMockTest_DoMove_0010"; + + std::string src; + std::string dest = "file.txt"; + optional mode = std::make_optional(MODE_FORCE_MOVE); + + int fd = open(dest.c_str(), O_RDWR | O_CREAT, 0666); + ASSERT_NE(fd, -1); + + EXPECT_CALL(*uvMock, uv_fs_access(_, _, _, _, _)).WillOnce(Return(1)); + EXPECT_CALL(*uvMock, uv_fs_rename(_, _, _, _, _)).WillOnce(Return(-1)); + EXPECT_CALL(*uvMock, uv_fs_stat(_, _, _, _)).WillOnce(Return(1)); + + auto res = MoveCore::DoMove(src, dest, mode); + EXPECT_EQ(res.IsSuccess(), false); + close(fd); + + GTEST_LOG_(INFO) << "MoveCoreMockTest-end MoveCoreMockTest_DoMove_0010"; +} + +/** + * @tc.name: MoveCoreMockTest_DoMove_0011 + * @tc.desc: Test function of MoveCore::DoMove interface for FALSE. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(MoveCoreMockTest, MoveCoreMockTest_DoMove_0011, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "MoveCoreMockTest-begin MoveCoreMockTest_DoMove_0011"; + + std::string src; + std::string dest; + optional mode = std::make_optional(MODE_FORCE_MOVE); + + EXPECT_CALL(*uvMock, uv_fs_access(_, _, _, _, _)).WillOnce(Return(1)); + EXPECT_CALL(*uvMock, uv_fs_rename(_, _, _, _, _)).WillOnce(Return(-1)); + EXPECT_CALL(*uvMock, uv_fs_stat(_, _, _, _)).WillOnce(Return(1)); + + auto res = MoveCore::DoMove(src, dest, mode); + EXPECT_EQ(res.IsSuccess(), false); + + GTEST_LOG_(INFO) << "MoveCoreMockTest-end MoveCoreMockTest_DoMove_0011"; +} + +/** + * @tc.name: MoveCoreMockTest_DoMove_0012 + * @tc.desc: Test function of MoveCore::DoMove interface for FALSE. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(MoveCoreMockTest, MoveCoreMockTest_DoMove_0012, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "MoveCoreMockTest-begin MoveCoreMockTest_DoMove_0012"; + + std::string src = "file.txt"; + std::string dest = "dest.txt"; + optional mode = std::make_optional(MODE_FORCE_MOVE); + + int fd = open(src.c_str(), O_RDWR | O_CREAT, 0666); + ASSERT_NE(fd, -1); + + EXPECT_CALL(*uvMock, uv_fs_access(_, _, _, _, _)).WillOnce(Return(1)); + EXPECT_CALL(*uvMock, uv_fs_rename(_, _, _, _, _)).WillOnce(Return(-1)); + EXPECT_CALL(*uvMock, uv_fs_stat(_, _, _, _)).WillOnce(Return(1)); + EXPECT_CALL(*uvMock, uv_fs_unlink(_, _, _, _)).WillOnce(Return(-1)).WillOnce(Return(-1)); + + auto res = MoveCore::DoMove(src, dest, mode); + EXPECT_EQ(res.IsSuccess(), false); + + ASSERT_EQ(unlink(src.c_str()), 0); + close(fd); + + GTEST_LOG_(INFO) << "MoveCoreMockTest-end MoveCoreMockTest_DoMove_0012"; +} + +/** + * @tc.name: MoveCoreMockTest_DoMove_0013 + * @tc.desc: Test function of MoveCore::DoMove interface for FALSE. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(MoveCoreMockTest, MoveCoreMockTest_DoMove_0013, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "MoveCoreMockTest-begin MoveCoreMockTest_DoMove_0013"; + + std::string src = "file.txt"; + std::string dest = "dest.txt"; + optional mode = std::make_optional(MODE_FORCE_MOVE); + + int fd = open(src.c_str(), O_RDWR | O_CREAT, 0666); + ASSERT_NE(fd, -1); + + EXPECT_CALL(*uvMock, uv_fs_access(_, _, _, _, _)).WillOnce(Return(1)); + EXPECT_CALL(*uvMock, uv_fs_rename(_, _, _, _, _)).WillOnce(Return(-1)); + EXPECT_CALL(*uvMock, uv_fs_stat(_, _, _, _)).WillOnce(Return(1)); + EXPECT_CALL(*uvMock, uv_fs_unlink(_, _, _, _)).WillOnce(Return(-1)).WillOnce(Return(1)); + + auto res = MoveCore::DoMove(src, dest, mode); + EXPECT_EQ(res.IsSuccess(), false); + + ASSERT_EQ(unlink(src.c_str()), 0); + close(fd); + + GTEST_LOG_(INFO) << "MoveCoreMockTest-end MoveCoreMockTest_DoMove_0013"; +} + +/** + * @tc.name: MoveCoreMockTest_DoMove_0014 + * @tc.desc: Test function of MoveCore::DoMove interface for SUCCESS. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(MoveCoreMockTest, MoveCoreMockTest_DoMove_0014, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "MoveCoreMockTest-begin MoveCoreMockTest_DoMove_0013"; + + std::string src = "file.txt"; + std::string dest = "dest.txt"; + optional mode = std::make_optional(MODE_FORCE_MOVE); + + int fd = open(src.c_str(), O_RDWR | O_CREAT, 0666); + ASSERT_NE(fd, -1); + + EXPECT_CALL(*uvMock, uv_fs_access(_, _, _, _, _)).WillOnce(Return(1)); + EXPECT_CALL(*uvMock, uv_fs_rename(_, _, _, _, _)).WillOnce(Return(-1)); + EXPECT_CALL(*uvMock, uv_fs_stat(_, _, _, _)).WillOnce(Return(1)); + EXPECT_CALL(*uvMock, uv_fs_unlink(_, _, _, _)).WillOnce(Return(1)); + + auto res = MoveCore::DoMove(src, dest, mode); + EXPECT_EQ(res.IsSuccess(), true); + + ASSERT_EQ(unlink(src.c_str()), 0); + close(fd); + + GTEST_LOG_(INFO) << "MoveCoreMockTest-end MoveCoreMockTest_DoMove_0013"; +} + + +} // namespace OHOS::FileManagement::ModuleFileIO::Test \ No newline at end of file diff --git a/interfaces/test/unittest/js/mod_fs/properties/move_core_test.cpp b/interfaces/test/unittest/js/mod_fs/properties/move_core_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e17eeaf30470bbdb237f7ea9f0c79a38de4b1414 --- /dev/null +++ b/interfaces/test/unittest/js/mod_fs/properties/move_core_test.cpp @@ -0,0 +1,166 @@ +/* + * Copyright (C) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "move_core.h" + +#include +#include + + +namespace OHOS::FileManagement::ModuleFileIO::Test { +using namespace testing; +using namespace testing::ext; +using namespace std; + +class MoveCoreTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); +}; + +void MoveCoreTest::SetUpTestCase(void) +{ + GTEST_LOG_(INFO) << "SetUpTestCase"; +} + +void MoveCoreTest::TearDownTestCase(void) +{ + GTEST_LOG_(INFO) << "TearDownTestCase"; +} + +void MoveCoreTest::SetUp(void) +{ + GTEST_LOG_(INFO) << "SetUp"; +} + +void MoveCoreTest::TearDown(void) +{ + GTEST_LOG_(INFO) << "TearDown"; +} + +/** + * @tc.name: MoveCoreTest_DoMove_001 + * @tc.desc: Test function of MoveCore::DoMove interface for ERROR. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(MoveCoreTest, MoveCoreTest_DoMove_001, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "MoveCoreTest-begin MoveCoreTest_DoMove_001"; + + std::string src = ""; + std::string dest = ""; + + auto res = MoveCore::DoMove(src, dest); + EXPECT_EQ(res.IsSuccess(), false); + + GTEST_LOG_(INFO) << "MoveCoreTest-end MoveCoreTest_DoMove_001"; +} + +/** + * @tc.name: MoveCoreTest_DoMove_002 + * @tc.desc: Test function of MoveCore::DoMove interface for ERROR. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(MoveCoreTest, MoveCoreTest_DoMove_002, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "MoveCoreTest-begin MoveCoreTest_DoMove_002"; + + std::string src = "/src.txt"; + std::string dest = ""; + + auto res = MoveCore::DoMove(src, dest); + EXPECT_EQ(res.IsSuccess(), false); + + GTEST_LOG_(INFO) << "MoveCoreTest-end MoveCoreTest_DoMove_002"; +} + +/** + * @tc.name: MoveCoreTest_DoMove_003 + * @tc.desc: Test function of MoveCore::DoMove interface for ERROR. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(MoveCoreTest, MoveCoreTest_DoMove_003, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "MoveCoreTest-begin MoveCoreTest_DoMove_003"; + + std::string src = "/src.txt"; + std::string dest = "/dest.txt"; + int mode = 3; + + auto res = MoveCore::DoMove(src, dest, mode); + EXPECT_EQ(res.IsSuccess(), false); + + GTEST_LOG_(INFO) << "MoveCoreTest-end MoveCoreTest_DoMove_003"; +} + +/** + * @tc.name: MoveCoreTest_DoMove_004 + * @tc.desc: Test function of MoveCore::DoMove interface for FALSE. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(MoveCoreTest, MoveCoreTest_DoMove_004, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "MoveCoreTest-begin MoveCoreTest_DoMove_004"; + + std::string src = "dir"; + std::string dest = "/dest.txt"; + int mode = 3; + + std::filesystem::path dirpath = "dir"; + ASSERT_TRUE(std::filesystem::create_directories(dirpath)); + + auto res = MoveCore::DoMove(src, dest, mode); + EXPECT_EQ(res.IsSuccess(), false); + + std::filesystem::remove(dirpath); + GTEST_LOG_(INFO) << "MoveCoreTest-end MoveCoreTest_DoMove_004"; +} + +/** + * @tc.name: MoveCoreTest_DoMove_005 + * @tc.desc: Test function of MoveCore::DoMove interface for FALSE. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(MoveCoreTest, MoveCoreTest_DoMove_005, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "MoveCoreTest-begin MoveCoreTest_DoMove_005"; + + std::string src = "/src.txt"; + std::string dest = "dir"; + int mode = 3; + + std::filesystem::path dirpath = "dir"; + ASSERT_TRUE(std::filesystem::create_directories(dirpath)); + + auto res = MoveCore::DoMove(src, dest, mode); + EXPECT_EQ(res.IsSuccess(), false); + + std::filesystem::remove(dirpath); + GTEST_LOG_(INFO) << "MoveCoreTest-end MoveCoreTest_DoMove_005"; +} + +} // namespace OHOS::FileManagement::ModuleFileIO::Test \ No newline at end of file diff --git a/interfaces/test/unittest/js/mod_fs/properties/open_core_mock_test.cpp b/interfaces/test/unittest/js/mod_fs/properties/open_core_mock_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..27cd727317dfc6a63ef724b06f2bd75f3fce3844 --- /dev/null +++ b/interfaces/test/unittest/js/mod_fs/properties/open_core_mock_test.cpp @@ -0,0 +1,146 @@ +/* + * Copyright (C) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "open_core.h" +#include "mock/uv_fs_mock.h" + +#include +#include +#include +#include + +namespace OHOS::FileManagement::ModuleFileIO::Test { +using namespace testing; +using namespace testing::ext; +using namespace std; + +class OpenCoreMockTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); + static inline shared_ptr uvMock = nullptr; +}; + +void OpenCoreMockTest::SetUpTestCase(void) +{ + GTEST_LOG_(INFO) << "SetUpTestCase"; + uvMock = std::make_shared(); + Uvfs::ins = uvMock; +} + +void OpenCoreMockTest::TearDownTestCase(void) +{ + GTEST_LOG_(INFO) << "TearDownTestCase"; + Uvfs::ins = nullptr; + uvMock = nullptr; +} + +void OpenCoreMockTest::SetUp(void) +{ + GTEST_LOG_(INFO) << "SetUp"; +} + +void OpenCoreMockTest::TearDown(void) +{ + GTEST_LOG_(INFO) << "TearDown"; +} + +/** +* @tc.name: OpenCoreMockTest_DoOpen_001 +* @tc.desc: Test function of OpenCore::DoOpen interface for SUCCESS. +* @tc.size: MEDIUM +* @tc.type: FUNC +* @tc.level Level 1 +*/ +HWTEST_F(OpenCoreMockTest, OpenCoreMockTest_DoOpen_001, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "OpenCoreMockTest-begin OpenCoreMockTest_DoOpen_001"; + + string path = "/test/open_test.txt"; + int32_t mode = 0; + + EXPECT_CALL(*uvMock, uv_fs_open(_, _, _, _, _, _)).WillOnce(Return(0)); + auto res = OpenCore::DoOpen(path, mode); + EXPECT_EQ(res.IsSuccess(), true); + + GTEST_LOG_(INFO) << "OpenCoreMockTest-end OpenCoreMockTest_DoOpen_001"; +} + +/** +* @tc.name: OpenCoreMockTest_DoOpen_002 +* @tc.desc: Test function of OpenCore::DoOpen interface for SUCCESS. +* @tc.size: MEDIUM +* @tc.type: FUNC +* @tc.level Level 1 +*/ +HWTEST_F(OpenCoreMockTest, OpenCoreMockTest_DoOpen_002, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "OpenCoreMockTest-begin OpenCoreMockTest_DoOpen_002"; + + string path = "file://test/open_test.txt"; + int32_t mode = 0; + + EXPECT_CALL(*uvMock, uv_fs_open(_, _, _, _, _, _)).WillOnce(Return(0)); + auto res = OpenCore::DoOpen(path, mode); + EXPECT_EQ(res.IsSuccess(), true); + + GTEST_LOG_(INFO) << "OpenCoreMockTest-end OpenCoreMockTest_DoOpen_002"; +} + +/** +* @tc.name: OpenCoreMockTest_DoOpen_003 +* @tc.desc: Test function of OpenCore::DoOpen interface for FALSE. +* @tc.size: MEDIUM +* @tc.type: FUNC +* @tc.level Level 1 +*/ +HWTEST_F(OpenCoreMockTest, OpenCoreMockTest_DoOpen_003, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "OpenCoreMockTest-begin OpenCoreMockTest_DoOpen_003"; + + string path = "file://test/open_test.txt"; + int32_t mode = 0; + + EXPECT_CALL(*uvMock, uv_fs_open(_, _, _, _, _, _)).WillOnce(Return(-1)); + auto res = OpenCore::DoOpen(path, mode); + EXPECT_EQ(res.IsSuccess(), false); + + GTEST_LOG_(INFO) << "OpenCoreMockTest-end OpenCoreMockTest_DoOpen_003"; +} + +/** +* @tc.name: OpenCoreMockTest_DoOpen_004 +* @tc.desc: Test function of OpenCore::DoOpen interface for ERROR. +* @tc.size: MEDIUM +* @tc.type: FUNC +* @tc.level Level 1 +*/ +HWTEST_F(OpenCoreMockTest, OpenCoreMockTest_DoOpen_004, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "OpenCoreMockTest-begin OpenCoreMockTest_DoOpen_004"; + + string path = "/test/open_test.txt"; + int32_t mode = 0; + + EXPECT_CALL(*uvMock, uv_fs_open(_, _, _, _, _, _)).WillOnce(Return(-1)); + auto res = OpenCore::DoOpen(path, mode); + EXPECT_EQ(res.IsSuccess(), false); + + GTEST_LOG_(INFO) << "OpenCoreMockTest-end OpenCoreMockTest_DoOpen_004"; +} + +} // namespace OHOS::FileManagement::ModuleFileIO::Test \ No newline at end of file diff --git a/interfaces/test/unittest/js/mod_fs/properties/open_core_test.cpp b/interfaces/test/unittest/js/mod_fs/properties/open_core_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..fcfc9019b4a768a80bbbf34f09202a4ef474340b --- /dev/null +++ b/interfaces/test/unittest/js/mod_fs/properties/open_core_test.cpp @@ -0,0 +1,193 @@ +/* + * Copyright (C) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include + +#include "open_core.h" + +namespace OHOS::FileManagement::ModuleFileIO::Test { +using namespace testing; +using namespace testing::ext; +using namespace std; + +class OpenCoreTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); +}; + +void OpenCoreTest::SetUpTestCase(void) +{ + GTEST_LOG_(INFO) << "SetUpTestCase"; +} + +void OpenCoreTest::TearDownTestCase(void) +{ + GTEST_LOG_(INFO) << "TearDownTestCase"; +} + +void OpenCoreTest::SetUp(void) +{ + GTEST_LOG_(INFO) << "SetUp"; +} + +void OpenCoreTest::TearDown(void) +{ + GTEST_LOG_(INFO) << "TearDown"; +} + +/** +* @tc.name: OpenCoreTest_DoOpen_001 +* @tc.desc: Test function of OpenCore::DoOpen interface for ERROR. +* @tc.size: MEDIUM +* @tc.type: FUNC +* @tc.level Level 1 +*/ +HWTEST_F(OpenCoreTest, OpenCoreTest_DoOpen_001, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "OpenCoreTest-begin OpenCoreTest_DoOpen_001"; + + string path = "/test/open_test.txt"; + int32_t mode = -1; + + auto res = OpenCore::DoOpen(path, mode); + EXPECT_EQ(res.IsSuccess(), false); + + GTEST_LOG_(INFO) << "OpenCoreTest-end OpenCoreTest_DoOpen_001"; +} + +/** +* @tc.name: OpenCoreTest_DoOpen_002 +* @tc.desc: Test function of OpenCore::DoOpen interface for ERROR. +* @tc.size: MEDIUM +* @tc.type: FUNC +* @tc.level Level 1 +*/ +HWTEST_F(OpenCoreTest, OpenCoreTest_DoOpen_002, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "OpenCoreTest-begin OpenCoreTest_DoOpen_002"; + + string path = "/test/open_test.txt"; + int32_t mode = 3; + + auto res = OpenCore::DoOpen(path, mode); + EXPECT_EQ(res.IsSuccess(), false); + + GTEST_LOG_(INFO) << "OpenCoreTest-end OpenCoreTest_DoOpen_002"; +} + +/** +* @tc.name: OpenCoreTest_DoOpen_003 +* @tc.desc: Test function of OpenCore::DoOpen interface for FALSE. +* @tc.size: MEDIUM +* @tc.type: FUNC +* @tc.level Level 1 +*/ +HWTEST_F(OpenCoreTest, OpenCoreTest_DoOpen_003, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "OpenCoreTest-begin OpenCoreTest_DoOpen_003"; + + string path = "file://media/open_test.jpg"; + int32_t mode = 0; + + auto res = OpenCore::DoOpen(path, mode); + EXPECT_EQ(res.IsSuccess(), false); + + GTEST_LOG_(INFO) << "OpenCoreTest-end OpenCoreTest_DoOpen_003"; +} + +/** +* @tc.name: OpenCoreTest_DoOpen_004 +* @tc.desc: Test function of OpenCore::DoOpen interface for FALSE. +* @tc.size: MEDIUM +* @tc.type: FUNC +* @tc.level Level 1 +*/ +HWTEST_F(OpenCoreTest, OpenCoreTest_DoOpen_004, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "OpenCoreTest-begin OpenCoreTest_DoOpen_004"; + + string path = "file://docs/open_test.pdf"; + int32_t mode = 0; + + auto res = OpenCore::DoOpen(path, mode); + EXPECT_EQ(res.IsSuccess(), false); + + GTEST_LOG_(INFO) << "OpenCoreTest-end OpenCoreTest_DoOpen_004"; +} + +/** +* @tc.name: OpenCoreTest_DoOpen_005 +* @tc.desc: Test function of OpenCore::DoOpen interface for FALSE. +* @tc.size: MEDIUM +* @tc.type: FUNC +* @tc.level Level 1 +*/ +HWTEST_F(OpenCoreTest, OpenCoreTest_DoOpen_005, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "OpenCoreTest-begin OpenCoreTest_DoOpen_005"; + + string path = "content://com.example.provider/open_test.txt"; + int32_t mode = 0; + + auto res = OpenCore::DoOpen(path, mode); + EXPECT_EQ(res.IsSuccess(), false); + + GTEST_LOG_(INFO) << "OpenCoreTest-end OpenCoreTest_DoOpen_005"; +} + +/** +* @tc.name: OpenCoreTest_DoOpen_006 +* @tc.desc: Test function of OpenCore::DoOpen interface for FALSE. +* @tc.size: MEDIUM +* @tc.type: FUNC +* @tc.level Level 1 +*/ +HWTEST_F(OpenCoreTest, OpenCoreTest_DoOpen_006, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "OpenCoreTest-begin OpenCoreTest_DoOpen_006"; + + string path = "datashare://media/open_test.jpg"; + int32_t mode = 0; + + auto res = OpenCore::DoOpen(path, mode); + EXPECT_EQ(res.IsSuccess(), false); + + GTEST_LOG_(INFO) << "OpenCoreTest-end OpenCoreTest_DoOpen_006"; +} + +/** +* @tc.name: OpenCoreTest_DoOpen_007 +* @tc.desc: Test function of OpenCore::DoOpen interface for FALSE. +* @tc.size: MEDIUM +* @tc.type: FUNC +* @tc.level Level 1 +*/ +HWTEST_F(OpenCoreTest, OpenCoreTest_DoOpen_007, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "OpenCoreTest-begin OpenCoreTest_DoOpen_007"; + + string path = "invalid://path/dir_test"; + int32_t mode = 0; + + auto res = OpenCore::DoOpen(path, mode); + EXPECT_EQ(res.IsSuccess(), false); + + GTEST_LOG_(INFO) << "OpenCoreTest-end OpenCoreTest_DoOpen_007"; +} + +} // namespace OHOS::FileManagement::ModuleFileIO::Test \ No newline at end of file diff --git a/interfaces/test/unittest/js/mod_fs/properties/read_core_mock_test.cpp b/interfaces/test/unittest/js/mod_fs/properties/read_core_mock_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b5e5506e00bbebb77bbe374230c30ab694ab325d --- /dev/null +++ b/interfaces/test/unittest/js/mod_fs/properties/read_core_mock_test.cpp @@ -0,0 +1,107 @@ +/* + * Copyright (C) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "read_core.h" +#include "uv_fs_mock.h" + +#include +#include +#include + +namespace OHOS::FileManagement::ModuleFileIO::Test { +using namespace testing; +using namespace testing::ext; +using namespace std; + +class ReadCoreMockTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); + static inline std::shared_ptr uvMock = nullptr; +}; + +void ReadCoreMockTest::SetUpTestCase(void) +{ + GTEST_LOG_(INFO) << "SetUpTestCase"; + uvMock = std::make_shared(); + Uvfs::ins = uvMock; +} + +void ReadCoreMockTest::TearDownTestCase(void) +{ + GTEST_LOG_(INFO) << "TearDownTestCase"; + Uvfs::ins = nullptr; + uvMock = nullptr; +} + +void ReadCoreMockTest::SetUp(void) +{ + GTEST_LOG_(INFO) << "SetUp"; +} + +void ReadCoreMockTest::TearDown(void) +{ + GTEST_LOG_(INFO) << "TearDown"; +} + +/** + * @tc.name: ReadCoreMockTest_DoRead_001 + * @tc.desc: Test function of ReadCore::DoRead interface for FALSE. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(ReadCoreMockTest, ReadCoreMockTest_DoRead_001, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ReadCoreMockTest-begin ReadCoreMockTest_DoRead_001"; + + int32_t fd = 1; + void *buf = nullptr; + ArrayBuffer arrayBuffer(buf, 0); + + EXPECT_CALL(*uvMock, uv_fs_read(_, _, _, _, _, _, _)).WillOnce(Return(-1)); + + auto res = ReadCore::DoRead(fd, arrayBuffer); + EXPECT_EQ(res.IsSuccess(), false); + + GTEST_LOG_(INFO) << "ReadCoreMockTest-end ReadCoreMockTest_DoRead_001"; +} + +/** + * @tc.name: ReadCoreMockTest_DoRead_002 + * @tc.desc: Test function of ReadCore::DoRead interface for SUCCESS. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(ReadCoreMockTest, ReadCoreMockTest_DoRead_002, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ReadCoreMockTest-begin ReadCoreMockTest_DoRead_002"; + + int32_t fd = 1; + void *buf = nullptr; + ArrayBuffer arrayBuffer(buf, 0); + + EXPECT_CALL(*uvMock, uv_fs_read(_, _, _, _, _, _, _)).WillOnce(Return(1)); + + auto res = ReadCore::DoRead(fd, arrayBuffer); + EXPECT_EQ(res.IsSuccess(), true); + + GTEST_LOG_(INFO) << "ReadCoreMockTest-end ReadCoreMockTest_DoRead_002"; +} + +} // namespace OHOS::FileManagement::ModuleFileIO::Test \ No newline at end of file diff --git a/interfaces/test/unittest/js/mod_fs/properties/read_core_test.cpp b/interfaces/test/unittest/js/mod_fs/properties/read_core_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8ecb653c52f1095f48bc6035421420dcc5ffad99 --- /dev/null +++ b/interfaces/test/unittest/js/mod_fs/properties/read_core_test.cpp @@ -0,0 +1,121 @@ +/* + * Copyright (C) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "read_core.h" + +#include +#include +#include + + +namespace OHOS::FileManagement::ModuleFileIO::Test { +using namespace testing; +using namespace testing::ext; +using namespace std; + +class ReadCoreTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); +}; + +void ReadCoreTest::SetUpTestCase(void) +{ + GTEST_LOG_(INFO) << "SetUpTestCase"; +} + +void ReadCoreTest::TearDownTestCase(void) +{ + GTEST_LOG_(INFO) << "TearDownTestCase"; +} + +void ReadCoreTest::SetUp(void) +{ + GTEST_LOG_(INFO) << "SetUp"; +} + +void ReadCoreTest::TearDown(void) +{ + GTEST_LOG_(INFO) << "TearDown"; +} + +/** + * @tc.name: ReadCoreTest_DoRead_001 + * @tc.desc: Test function of ReadCore::DoRead interface for SUCCESS. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(ReadCoreTest, ReadCoreTest_DoRead_001, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ReadCoreTest-begin ReadCoreTest_DoRead_001"; + + int32_t fd = -1; + void *buf = nullptr; + ArrayBuffer arrayBuffer(buf, 0); + + auto res = ReadCore::DoRead(fd, arrayBuffer); + EXPECT_EQ(res.IsSuccess(), false); + + GTEST_LOG_(INFO) << "ReadCoreTest-end ReadCoreTest_DoRead_001"; +} + +/** + * @tc.name: ReadCoreTest_DoRead_002 + * @tc.desc: Test function of ReadCore::DoRead interface for SUCCESS. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(ReadCoreTest, ReadCoreTest_DoRead_002, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ReadCoreTest-begin ReadCoreTest_DoRead_002"; + + int32_t fd = 1; + void *buf = nullptr; + ArrayBuffer arrayBuffer(buf, 0xffffffff + 1); + + auto res = ReadCore::DoRead(fd, arrayBuffer); + EXPECT_EQ(res.IsSuccess(), false); + + GTEST_LOG_(INFO) << "ReadCoreTest-end ReadCoreTest_DoRead_002"; +} + +/** + * @tc.name: ReadCoreTest_DoRead_003 + * @tc.desc: Test function of ReadCore::DoRead interface for SUCCESS. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(ReadCoreTest, ReadCoreTest_DoRead_003, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ReadCoreTest-begin ReadCoreTest_DoRead_003"; + + int32_t fd = 1; + void *buf = nullptr; + ArrayBuffer arrayBuffer(buf, 0); + optional options = std::make_optional(); + options->offset = std::make_optional(-1); + + auto res = ReadCore::DoRead(fd, arrayBuffer, options); + EXPECT_EQ(res.IsSuccess(), false); + + GTEST_LOG_(INFO) << "ReadCoreTest-end ReadCoreTest_DoRead_003"; +} + +} // namespace OHOS::FileManagement::ModuleFileIO::Test \ No newline at end of file diff --git a/interfaces/test/unittest/js/mod_fs/properties/read_text_core_test.cpp b/interfaces/test/unittest/js/mod_fs/properties/read_text_core_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..56b6e4bb352dd1cb9eda26155c25551b0d1c26ef --- /dev/null +++ b/interfaces/test/unittest/js/mod_fs/properties/read_text_core_test.cpp @@ -0,0 +1,246 @@ +/* +* Copyright (c) 2025 Huawei Device Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +#include +#include + +#define FILE_INFO "hello world" +#define FILE_PATH "/data/test/ReadTextCoreTest.txt" + +namespace OHOS { +namespace FileManagement { +namespace ModuleFileIO { +using namespace std; + +const string content = "hello world"; + +class ReadTextCoreTest : public testing::Test { +public: + static void SetUpTestCase(void) + { + int32_t fd = open(FILE_PATH, CREATE | O_RDWR, 0644); + write(fd, content.c_str(), content.length()); + close(fd); + }; + static void TearDownTestCase() + { + rmdir(FILE_PATH); + }; + void SetUp() {}; + void TearDown() {}; +}; +/** +* @tc.name: DoReadTextTest_0001 +* @tc.desc: Test function of DoReadText() interface for single argument. +* @tc.size: MEDIUM +* @tc.type: FUNC +* @tc.level Level 1 +* @tc.require: AR000IGDNF +*/ +HWTEST_F(ReadTextCoreTest, DoReadTextTest_0001, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ReadTextCoreTest-begin DoReadTextTest_0001"; + auto ret = ReadTextCore::DoReadText(FILE_PATH); + EXPECT_TRUE(ret.IsSuccess()); + + const auto &resText = ret.GetData().value(); + string res = std::get<0>(resText); + EXPECT_EQ(res, FILE_INFO); + + GTEST_LOG_(INFO) << "ReadTextCoreTest-end DoReadTextTest_0001"; +} + +/** +* @tc.name: DoReadTextTest_0002 +* @tc.desc: Test function of DoReadText() interface for invalid offset. +* @tc.size: MEDIUM +* @tc.type: FUNC +* @tc.level Level 1 +* @tc.require: AR000IGDNF +*/ +HWTEST_F(ReadTextCoreTest, DoReadTextTest_0002, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ReadTextCoreTest-begin DoReadTextTest_0002"; + ReadTextOptions options; + options.offset = -1; + auto ret = ReadTextCore::DoReadText(FILE_PATH, options); + EXPECT_FALSE(ret.IsSuccess()); + + auto err = ret.GetError(); + EXPECT_EQ(err.GetErrNo(), 13900020); + + GTEST_LOG_(INFO) << "ReadTextCoreTest-end DoReadTextTest_0002"; +} + +/** +* @tc.name: DoReadTextTest_0003 +* @tc.desc: Test function of DoReadText() interface for invalid length < 0. +* @tc.size: MEDIUM +* @tc.type: FUNC +* @tc.level Level 1 +* @tc.require: AR000IGDNF +*/ +HWTEST_F(ReadTextCoreTest, DoReadTextTest_0003, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ReadTextCoreTest-begin DoReadTextTest_0003"; + ReadTextOptions options; + options.length = -5; + auto ret = ReadTextCore::DoReadText(FILE_PATH, options); + EXPECT_FALSE(ret.IsSuccess()); + + auto err = ret.GetError(); + EXPECT_EQ(err.GetErrNo(), 13900020); + + GTEST_LOG_(INFO) << "ReadTextCoreTest-end DoReadTextTest_0003"; +} + +/** +* @tc.name: DoReadTextTest_0004 +* @tc.desc: Test function of DoReadText() interface for invalid length > UINT_MAX. +* @tc.size: MEDIUM +* @tc.type: FUNC +* @tc.level Level 1 +* @tc.require: AR000IGDNF +*/ +HWTEST_F(ReadTextCoreTest, DoReadTextTest_0004, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ReadTextCoreTest-begin DoReadTextTest_0004"; + ReadTextOptions options; + options.length = static_cast(UINT_MAX) + 1; + auto ret = ReadTextCore::DoReadText(FILE_PATH, options); + EXPECT_FALSE(ret.IsSuccess()); + + auto err = ret.GetError(); + EXPECT_EQ(err.GetErrNo(), 13900020); + + GTEST_LOG_(INFO) << "ReadTextCoreTest-end DoReadTextTest_0004"; +} + +/** +* @tc.name: DoReadTextTest_0005 +* @tc.desc: Test function of DoReadText() interface for invalid encoding. +* @tc.size: MEDIUM +* @tc.type: FUNC +* @tc.level Level 1 +* @tc.require: AR000IGDNF +*/ +HWTEST_F(ReadTextCoreTest, DoReadTextTest_0005, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ReadTextCoreTest-begin DoReadTextTest_0005"; + ReadTextOptions options; + options.encoding = "gbk"; + auto ret = ReadTextCore::DoReadText(FILE_PATH, options); + EXPECT_FALSE(ret.IsSuccess()); + + auto err = ret.GetError(); + EXPECT_EQ(err.GetErrNo(), 13900020); + + GTEST_LOG_(INFO) << "ReadTextCoreTest-end DoReadTextTest_0005"; +} + +/** +* @tc.name: DoReadTextTest_0006 +* @tc.desc: Test function of DoReadText() interface for no such file or directory. +* @tc.size: MEDIUM +* @tc.type: FUNC +* @tc.level Level 1 +* @tc.require: AR000IGDNF +*/ +HWTEST_F(ReadTextCoreTest, DoReadTextTest_0006, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ReadTextCoreTest-begin DoReadTextTest_0006"; + auto ret = ReadTextCore::DoReadText("ReadTextCoreTest-begin-DoReadTextTest_0006.txt"); + EXPECT_FALSE(ret.IsSuccess()); + + auto err = ret.GetError(); + EXPECT_EQ(err.GetErrNo(), 13900002); + + GTEST_LOG_(INFO) << "ReadTextCoreTest-end DoReadTextTest_0006"; +} + +/** +* @tc.name: DoReadTextTest_0007 +* @tc.desc: Test function of DoReadText() interface for huge offset. +* @tc.size: MEDIUM +* @tc.type: FUNC +* @tc.level Level 1 +* @tc.require: AR000IGDNF +*/ +HWTEST_F(ReadTextCoreTest, DoReadTextTest_0007, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ReadTextCoreTest-begin DoReadTextTest_0007"; + ReadTextOptions options; + options.offset = 1000000; // 假设文件较小 + auto ret = ReadTextCore::DoReadText(FILE_PATH, options); + EXPECT_FALSE(ret.IsSuccess()); + + auto err = ret.GetError(); + EXPECT_EQ(err.GetErrNo(), 13900020); + + GTEST_LOG_(INFO) << "ReadTextCoreTest-end DoReadTextTest_0007"; +} + +/** +* @tc.name: DoReadTextTest_0008 +* @tc.desc: Test function of DoReadText() interface for no such file or directory. +* @tc.size: MEDIUM +* @tc.type: FUNC +* @tc.level Level 1 +* @tc.require: AR000IGDNF +*/ +HWTEST_F(ReadTextCoreTest, DoReadTextTest_0008, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ReadTextCoreTest-begin DoReadTextTest_0008"; + ReadTextOptions options; + options.length = 1000000; // 超过实际大小 + auto ret = ReadTextCore::DoReadText(FILE_PATH, options); + ASSERT_TRUE(ret.IsSuccess()); + + const auto &resText = ret.GetData().value(); + string res = std::get<0>(resText); + EXPECT_EQ(res, FILE_INFO); + + GTEST_LOG_(INFO) << "ReadTextCoreTest-end DoReadTextTest_0008"; +} + +/** +* @tc.name: DoReadTextTest_0009 +* @tc.desc: Test function of DoReadText() interface for success. +* @tc.size: MEDIUM +* @tc.type: FUNC +* @tc.level Level 1 +* @tc.require: AR000IGDNF +*/ +HWTEST_F(ReadTextCoreTest, DoReadTextTest_0009, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ReadTextCoreTest-begin DoReadTextTest_0009"; + ReadTextOptions options; + options.offset = 2; + options.length = 5; + auto ret = ReadTextCore::DoReadText(FILE_PATH, options); + ASSERT_TRUE(ret.IsSuccess()); + + const auto &resText = ret.GetData().value(); + string res = std::get<0>(resText); + std::string extracted = std::string(FILE_INFO).substr( + options.offset.value(), options.length.value()); + EXPECT_EQ(res, extracted); + + GTEST_LOG_(INFO) << "ReadTextCoreTest-end DoReadTextTest_0009"; +} + +} +} +} \ No newline at end of file diff --git a/interfaces/test/unittest/js/mod_fs/properties/rmdir_core_test.cpp b/interfaces/test/unittest/js/mod_fs/properties/rmdir_core_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..0cbdf7ebd35e4e003d3c69cbd68631cc53a3e2e0 --- /dev/null +++ b/interfaces/test/unittest/js/mod_fs/properties/rmdir_core_test.cpp @@ -0,0 +1,168 @@ +/* + * Copyright (C) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "rmdir_core.h" + +#include +#include +#include + + +namespace OHOS::FileManagement::ModuleFileIO::Test { +using namespace testing; +using namespace testing::ext; +using namespace std; + +class RmdirCoreTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); +}; + +void RmdirCoreTest::SetUpTestCase(void) +{ + GTEST_LOG_(INFO) << "SetUpTestCase"; +} + +void RmdirCoreTest::TearDownTestCase(void) +{ + GTEST_LOG_(INFO) << "TearDownTestCase"; +} + +void RmdirCoreTest::SetUp(void) +{ + GTEST_LOG_(INFO) << "SetUp"; +} + +void RmdirCoreTest::TearDown(void) +{ + GTEST_LOG_(INFO) << "TearDown"; +} + +/** + * @tc.name: RmdirCoreTest_DoRmdirent_001 + * @tc.desc: Test function of RmdirCore::DoRmdirent interface for Failed. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(RmdirCoreTest, RmdirCoreTest_DoRmdirent_001, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "RmdirCoreTest-begin RmdirCoreTest_DoRmdirent_001"; + std::string fpath; + auto res = RmdirentCore::DoRmdirent(fpath); + + EXPECT_EQ(res.IsSuccess(), false); + + GTEST_LOG_(INFO) << "RmdirCoreTest-end RmdirCoreTest_DoRmdirent_001"; +} + +/** + * @tc.name: RmdirCoreTest_DoRmdirent_002 + * @tc.desc: Test function of RmdirCore::DoRmdirent interface for Failed. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(RmdirCoreTest, RmdirCoreTest_DoRmdirent_002, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "RmdirCoreTest-begin RmdirCoreTest_DoRmdirent_002"; + std::string fpath = "invalid?path"; + auto res = RmdirentCore::DoRmdirent(fpath); + + EXPECT_EQ(res.IsSuccess(), false); + + GTEST_LOG_(INFO) << "RmdirCoreTest-end RmdirCoreTest_DoRmdirent_002"; +} + +/** + * @tc.name: RmdirCoreTest_DoRmdirent_003 + * @tc.desc: Test function of RmdirCore::DoRmdirent interface for Failed. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(RmdirCoreTest, RmdirCoreTest_DoRmdirent_003, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "RmdirCoreTest-begin RmdirCoreTest_DoRmdirent_003"; + std::string fpath = "/dir"; + auto res = RmdirentCore::DoRmdirent(fpath); + + EXPECT_EQ(res.IsSuccess(), false); + + GTEST_LOG_(INFO) << "RmdirCoreTest-end RmdirCoreTest_DoRmdirent_003"; +} + +/** + * @tc.name: RmdirCoreTest_DoRmdirent_004 + * @tc.desc: Test function of RmdirCore::DoRmdirent interface for Failed. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(RmdirCoreTest, RmdirCoreTest_DoRmdirent_004, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "RmdirCoreTest-begin RmdirCoreTest_DoRmdirent_004"; + + std::filesystem::create_directories("test_dir"); + std::ofstream("test_dir/test_file.txt") << "test"; + + std::filesystem::permissions("test_dir", + std::filesystem::perms::owner_write | std::filesystem::perms::owner_exec, + std::filesystem::perm_options::replace); + + auto res = RmdirentCore::DoRmdirent("test_dir"); + EXPECT_EQ(res.IsSuccess(), true); + + try { + std::filesystem::permissions("test_dir", + std::filesystem::perms::owner_all, + std::filesystem::perm_options::replace); + } catch (...) {} + std::filesystem::remove_all("test_dir"); + + GTEST_LOG_(INFO) << "RmdirCoreTest-end RmdirCoreTest_DoRmdirent_004"; +} + +/** + * @tc.name: RmdirCoreTest_DoRmdirent_005 + * @tc.desc: Test function of RmdirCore::DoRmdirent interface for SUCCESS. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(RmdirCoreTest, RmdirCoreTest_DoRmdirent_005, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "RmdirCoreTest-begin RmdirCoreTest_DoRmdirent_005"; + + std::filesystem::create_directories("test_dir"); + std::ofstream("test_dir/test_file.txt") << "test"; + + auto res = RmdirentCore::DoRmdirent("test_dir"); + EXPECT_EQ(res.IsSuccess(), true); + + try { + std::filesystem::permissions("test_dir", + std::filesystem::perms::owner_all, + std::filesystem::perm_options::replace); + } catch (...) {} + std::filesystem::remove_all("test_dir"); + + GTEST_LOG_(INFO) << "RmdirCoreTest-end RmdirCoreTest_DoRmdirent_005"; +} + +} // namespace OHOS::FileManagement::ModuleFileIO::Test \ No newline at end of file diff --git a/interfaces/test/unittest/js/mod_fs/properties/stat_core_mock_test.cpp b/interfaces/test/unittest/js/mod_fs/properties/stat_core_mock_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..2fd8bd7f5a0fc91f34abf631095019ddbb5e7a9f --- /dev/null +++ b/interfaces/test/unittest/js/mod_fs/properties/stat_core_mock_test.cpp @@ -0,0 +1,156 @@ +/* + * Copyright (C) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "securec.h" +#include "stat_core.h" +#include "uv_fs_mock.h" + +#include + +namespace OHOS::FileManagement::ModuleFileIO::Test { +using namespace testing; +using namespace testing::ext; +using namespace std; + +class StatCoreMockTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); + static inline shared_ptr uvfs = nullptr; +}; + +void StatCoreMockTest::SetUpTestCase(void) +{ + uvfs = std::make_shared(); + Uvfs::ins = uvfs; + GTEST_LOG_(INFO) << "SetUpTestCase"; +} + +void StatCoreMockTest::TearDownTestCase(void) +{ + Uvfs::ins = nullptr; + uvfs = nullptr; + GTEST_LOG_(INFO) << "TearDownTestCase"; +} + +void StatCoreMockTest::SetUp(void) +{ + GTEST_LOG_(INFO) << "SetUp"; +} + +void StatCoreMockTest::TearDown(void) +{ + GTEST_LOG_(INFO) << "TearDown"; +} + +/** + * @tc.name: StatCoreMockTest_DoStat_001 + * @tc.desc: Test function of FsyncCore::DoStat interface for FALSE. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(StatCoreMockTest, StatCoreMockTest_DoStat_001, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "StatCoreMockTest-begin StatCoreMockTest_DoStat_001"; + + FileInfo fileinfo; + fileinfo.path = std::make_unique(1); + fileinfo.isPath = true; + + EXPECT_CALL(*uvfs, uv_fs_stat(_, _, _, _)).WillOnce(Return(-1)); + + auto res = StatCore::DoStat(fileinfo); + EXPECT_EQ(res.IsSuccess(), false); + + GTEST_LOG_(INFO) << "StatCoreMockTest-end StatCoreMockTest_DoStat_001"; +} + +/** + * @tc.name: StatCoreMockTest_DoStat_002 + * @tc.desc: Test function of FsyncCore::DoStat interface for FALSE. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(StatCoreMockTest, StatCoreMockTest_DoStat_002, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "StatCoreMockTest-begin StatCoreMockTest_DoStat_002"; + + FileInfo fileinfo; + fileinfo.path = std::make_unique(1); + fileinfo.isPath = true; + + EXPECT_CALL(*uvfs, uv_fs_stat(_, _, _, _)).WillOnce(Return(1)); + + auto res = StatCore::DoStat(fileinfo); + EXPECT_EQ(res.IsSuccess(), false); + + GTEST_LOG_(INFO) << "StatCoreMockTest-end StatCoreMockTest_DoStat_002"; +} + +/** + * @tc.name: StatCoreMockTest_DoStat_003 + * @tc.desc: Test function of FsyncCore::DoStat interface for FALSE. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(StatCoreMockTest, StatCoreMockTest_DoStat_003, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "StatCoreMockTest-begin StatCoreMockTest_DoStat_003"; + + FileInfo fileinfo; + fileinfo.path = std::make_unique(1); + fileinfo.isPath = false; + + EXPECT_CALL(*uvfs, uv_fs_stat(_, _, _, _)).WillOnce(Return(-1)); + + auto res = StatCore::DoStat(fileinfo); + EXPECT_EQ(res.IsSuccess(), false); + + GTEST_LOG_(INFO) << "StatCoreMockTest-end StatCoreMockTest_DoStat_003"; +} + +/** + * @tc.name: StatCoreMockTest_DoStat_005 + * @tc.desc: Test function of FsyncCore::DoStat interface for FALSE. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(StatCoreMockTest, StatCoreMockTest_DoStat_005, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "StatCoreMockTest-begin StatCoreMockTest_DoStat_005"; + + FileInfo fileinfo; + string buffer = "Hello, World!"; + int pathLength = buffer.size() + 1; + fileinfo.path = std::make_unique(pathLength); + memcpy_s(fileinfo.path.get(), pathLength, buffer.c_str(), buffer.size()); + fileinfo.fdg = std::make_unique(-1); + fileinfo.isPath = true; + + EXPECT_CALL(*uvfs, uv_fs_stat(_, _, _, _)).WillOnce(Return(-1)); + + auto res = StatCore::DoStat(fileinfo); + EXPECT_EQ(res.IsSuccess(), false); + + GTEST_LOG_(INFO) << "StatCoreMockTest-end StatCoreMockTest_DoStat_005"; +} + +} // namespace OHOS::FileManagement::ModuleFileIO::Test \ No newline at end of file diff --git a/interfaces/test/unittest/js/mod_fs/properties/stat_core_test.cpp b/interfaces/test/unittest/js/mod_fs/properties/stat_core_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..5ad93fbf97b015b70ea49f13ee7815935ddb768e --- /dev/null +++ b/interfaces/test/unittest/js/mod_fs/properties/stat_core_test.cpp @@ -0,0 +1,94 @@ +/* + * Copyright (C) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "stat_core.h" + +#include + +namespace OHOS::FileManagement::ModuleFileIO::Test { +using namespace testing; +using namespace testing::ext; +using namespace std; + +class StatCoreTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); +}; + +void StatCoreTest::SetUpTestCase(void) +{ + GTEST_LOG_(INFO) << "SetUpTestCase"; +} + +void StatCoreTest::TearDownTestCase(void) +{ + GTEST_LOG_(INFO) << "TearDownTestCase"; +} + +void StatCoreTest::SetUp(void) +{ + GTEST_LOG_(INFO) << "SetUp"; +} + +void StatCoreTest::TearDown(void) +{ + GTEST_LOG_(INFO) << "TearDown"; +} + +/** + * @tc.name: StatCoreTest_DoStat_001 + * @tc.desc: Test function of FsyncCore::DoStat interface for FALSE. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(StatCoreTest, StatCoreTest_DoStat_001, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "StatCoreTest-begin StatCoreTest_DoStat_001"; + + FileInfo fileinfo; + + auto res = StatCore::DoStat(fileinfo); + EXPECT_EQ(res.IsSuccess(), false); + + GTEST_LOG_(INFO) << "StatCoreTest-end StatCoreTest_DoStat_001"; +} + +/** + * @tc.name: StatCoreTest_DoStat_002 + * @tc.desc: Test function of FsyncCore::DoStat interface for FALSE. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(StatCoreTest, StatCoreTest_DoStat_002, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "StatCoreTest-begin StatCoreTest_DoStat_002"; + + FileInfo fileinfo; + fileinfo.path = std::make_unique(1); + fileinfo.fdg = std::make_unique(-1); + fileinfo.isPath = false; + + auto res = StatCore::DoStat(fileinfo); + EXPECT_EQ(res.IsSuccess(), false); + + GTEST_LOG_(INFO) << "StatCoreTest-end StatCoreTest_DoStat_002"; +} + +} // namespace OHOS::FileManagement::ModuleFileIO::Test \ No newline at end of file diff --git a/interfaces/test/unittest/js/mod_fs/properties/truncate_core_mock_test.cpp b/interfaces/test/unittest/js/mod_fs/properties/truncate_core_mock_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..15181a63d61087602ddc4e1540b1dc4ab1aef52b --- /dev/null +++ b/interfaces/test/unittest/js/mod_fs/properties/truncate_core_mock_test.cpp @@ -0,0 +1,169 @@ +/* + * Copyright (C) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "truncate_core.h" +#include "uv_fs_mock.h" + +#include + +namespace OHOS::FileManagement::ModuleFileIO::Test { +using namespace testing; +using namespace testing::ext; +using namespace std; + +class TruncateCoreMockTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); + static inline shared_ptr uvMock = nullptr; +}; + +void TruncateCoreMockTest::SetUpTestCase(void) +{ + GTEST_LOG_(INFO) << "SetUpTestCase"; + uvMock = std::make_shared(); + Uvfs::ins = uvMock; +} + +void TruncateCoreMockTest::TearDownTestCase(void) +{ + GTEST_LOG_(INFO) << "TearDownTestCase"; + Uvfs::ins = nullptr; + uvMock = nullptr; +} + +void TruncateCoreMockTest::SetUp(void) +{ + GTEST_LOG_(INFO) << "SetUp"; +} + +void TruncateCoreMockTest::TearDown(void) +{ + GTEST_LOG_(INFO) << "TearDown"; +} + +/** + * @tc.name: TruncateCoreMockTest_DoTruncate_001 + * @tc.desc: Test function of RmdirCore::DoTruncate interface for Failed. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(TruncateCoreMockTest, TruncateCoreMockTest_DoTruncate_001, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "TruncateCoreMockTest-begin TruncateCoreMockTest_DoTruncate_001"; + + FileInfo fileInfo; + fileInfo.isPath = true; + fileInfo.fdg = std::make_unique(1); + + EXPECT_CALL(*uvMock, uv_fs_open(_, _, _, _, _, _)).WillOnce(Return(-1)); + auto res = TruncateCore::DoTruncate(fileInfo); + EXPECT_EQ(res.IsSuccess(), false); + + GTEST_LOG_(INFO) << "TruncateCoreMockTest-end TruncateCoreMockTest_DoTruncate_001"; +} + +/** + * @tc.name: TruncateCoreMockTest_DoTruncate_002 + * @tc.desc: Test function of RmdirCore::DoTruncate interface for Failed. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(TruncateCoreMockTest, TruncateCoreMockTest_DoTruncate_002, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "TruncateCoreMockTest-begin TruncateCoreMockTest_DoTruncate_002"; + + FileInfo fileInfo; + fileInfo.isPath = true; + fileInfo.fdg = std::make_unique(1); + + EXPECT_CALL(*uvMock, uv_fs_open(_, _, _, _, _, _)).WillOnce(Return(1)); + EXPECT_CALL(*uvMock, uv_fs_ftruncate(_, _, _, _, _)).WillOnce(Return(-1)); + auto res = TruncateCore::DoTruncate(fileInfo); + EXPECT_EQ(res.IsSuccess(), false); + + GTEST_LOG_(INFO) << "TruncateCoreMockTest-end TruncateCoreMockTest_DoTruncate_002"; +} + +/** + * @tc.name: TruncateCoreMockTest_DoTruncate_003 + * @tc.desc: Test function of RmdirCore::DoTruncate interface for SUCCESS. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(TruncateCoreMockTest, TruncateCoreMockTest_DoTruncate_003, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "TruncateCoreMockTest-begin TruncateCoreMockTest_DoTruncate_003"; + + FileInfo fileInfo; + fileInfo.isPath = true; + fileInfo.fdg = std::make_unique(1); + + EXPECT_CALL(*uvMock, uv_fs_open(_, _, _, _, _, _)).WillOnce(Return(1)); + EXPECT_CALL(*uvMock, uv_fs_ftruncate(_, _, _, _, _)).WillOnce(Return(1)); + auto res = TruncateCore::DoTruncate(fileInfo); + EXPECT_EQ(res.IsSuccess(), true); + + GTEST_LOG_(INFO) << "TruncateCoreMockTest-end TruncateCoreMockTest_DoTruncate_003"; +} + +/** + * @tc.name: TruncateCoreMockTest_DoTruncate_004 + * @tc.desc: Test function of RmdirCore::DoTruncate interface for FALSE. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(TruncateCoreMockTest, TruncateCoreMockTest_DoTruncate_004, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "TruncateCoreMockTest-begin TruncateCoreMockTest_DoTruncate_004"; + + FileInfo fileInfo; + fileInfo.fdg = std::make_unique(1); + + EXPECT_CALL(*uvMock, uv_fs_ftruncate(_, _, _, _, _)).WillOnce(Return(-1)); + auto res = TruncateCore::DoTruncate(fileInfo); + EXPECT_EQ(res.IsSuccess(), false); + + GTEST_LOG_(INFO) << "TruncateCoreMockTest-end TruncateCoreMockTest_DoTruncate_004"; +} + +/** + * @tc.name: TruncateCoreMockTest_DoTruncate_005 + * @tc.desc: Test function of RmdirCore::DoTruncate interface for SUCCESS. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(TruncateCoreMockTest, TruncateCoreMockTest_DoTruncate_005, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "TruncateCoreMockTest-begin TruncateCoreMockTest_DoTruncate_005"; + + FileInfo fileInfo; + fileInfo.fdg = std::make_unique(1); + + EXPECT_CALL(*uvMock, uv_fs_ftruncate(_, _, _, _, _)).WillOnce(Return(1)); + auto res = TruncateCore::DoTruncate(fileInfo); + EXPECT_EQ(res.IsSuccess(), true); + + GTEST_LOG_(INFO) << "TruncateCoreMockTest-end TruncateCoreMockTest_DoTruncate_005"; +} + +} // namespace OHOS::FileManagement::ModuleFileIO::Test \ No newline at end of file diff --git a/interfaces/test/unittest/js/mod_fs/properties/truncate_core_test.cpp b/interfaces/test/unittest/js/mod_fs/properties/truncate_core_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b9a98e51fe0f98d7f0926da279c754f8eabce463 --- /dev/null +++ b/interfaces/test/unittest/js/mod_fs/properties/truncate_core_test.cpp @@ -0,0 +1,93 @@ +/* + * Copyright (C) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "truncate_core.h" + +#include + + +namespace OHOS::FileManagement::ModuleFileIO::Test { +using namespace testing; +using namespace testing::ext; +using namespace std; + +class TruncateCoreTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); +}; + +void TruncateCoreTest::SetUpTestCase(void) +{ + GTEST_LOG_(INFO) << "SetUpTestCase"; +} + +void TruncateCoreTest::TearDownTestCase(void) +{ + GTEST_LOG_(INFO) << "TearDownTestCase"; +} + +void TruncateCoreTest::SetUp(void) +{ + GTEST_LOG_(INFO) << "SetUp"; +} + +void TruncateCoreTest::TearDown(void) +{ + GTEST_LOG_(INFO) << "TearDown"; +} + +/** + * @tc.name: TruncateCoreTest_DoTruncate_001 + * @tc.desc: Test function of RmdirCore::DoTruncate interface for Failed. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(TruncateCoreTest, TruncateCoreTest_DoTruncate_001, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "TruncateCoreTest-begin TruncateCoreTest_DoTruncate_001"; + FileInfo fileInfo; + fileInfo.fdg = std::make_unique(-1); + + auto res = TruncateCore::DoTruncate(fileInfo); + EXPECT_EQ(res.IsSuccess(), false); + + GTEST_LOG_(INFO) << "TruncateCoreTest-end TruncateCoreTest_DoTruncate_001"; +} + +/** + * @tc.name: TruncateCoreTest_DoTruncate_002 + * @tc.desc: Test function of RmdirCore::DoTruncate interface for Failed. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(TruncateCoreTest, TruncateCoreTest_DoTruncate_002, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "TruncateCoreTest-begin TruncateCoreTest_DoTruncate_002"; + FileInfo fileInfo; + std::optional len = std::make_optional(static_cast(-1)); + fileInfo.fdg = std::make_unique(1); + + auto res = TruncateCore::DoTruncate(fileInfo, len); + EXPECT_EQ(res.IsSuccess(), false); + + GTEST_LOG_(INFO) << "TruncateCoreTest-end TruncateCoreTest_DoTruncate_002"; +} + +} // namespace OHOS::FileManagement::ModuleFileIO::Test \ No newline at end of file diff --git a/interfaces/test/unittest/js/mod_fs/properties/unlink_core_mock_test.cpp b/interfaces/test/unittest/js/mod_fs/properties/unlink_core_mock_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d6103bee95cadbf641323bf2985162605a25b668 --- /dev/null +++ b/interfaces/test/unittest/js/mod_fs/properties/unlink_core_mock_test.cpp @@ -0,0 +1,108 @@ +/* + * Copyright (C) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include +#include + +#include "mock/uv_fs_mock.h" +#include "unlink_core.h" + +namespace OHOS::FileManagement::ModuleFileIO::Test { +using namespace testing; +using namespace testing::ext; +using namespace std; + +class UnlinkCoreMockTest : public testing::Test { +public: + static filesystem::path tempFilePath; + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); + static inline shared_ptr uvMock = nullptr; +}; + +filesystem::path UnlinkCoreMockTest::tempFilePath; + +void UnlinkCoreMockTest::SetUpTestCase(void) +{ + GTEST_LOG_(INFO) << "SetUpTestCase"; + tempFilePath = filesystem::temp_directory_path() / "unlink_test_file.txt"; + ofstream(tempFilePath) << "Test content\n123\n456"; + uvMock = std::make_shared(); + Uvfs::ins = uvMock; +} + +void UnlinkCoreMockTest::TearDownTestCase(void) +{ + GTEST_LOG_(INFO) << "TearDownTestCase"; + filesystem::remove(tempFilePath); + Uvfs::ins = nullptr; + uvMock = nullptr; +} + +void UnlinkCoreMockTest::SetUp(void) +{ + GTEST_LOG_(INFO) << "SetUp"; +} + +void UnlinkCoreMockTest::TearDown(void) +{ + GTEST_LOG_(INFO) << "TearDown"; +} + +/** + * @tc.name: UnlinkCoreMockTest_DoUnlink_001 + * @tc.desc: Test function of UnlinkCore::DoUnlink interface for SUCCESS. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(UnlinkCoreMockTest, UnlinkCoreMockTest_DoUnlink_001, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "UnlinkCoreMockTest-begin UnlinkCoreMockTest_DoUnlink_001"; + + EXPECT_CALL(*uvMock, uv_fs_unlink(_, _, _, _)).WillOnce(Return(1)); + + string path = tempFilePath.string(); + auto res = UnlinkCore::DoUnlink(path); + EXPECT_EQ(res.IsSuccess(), true); + + GTEST_LOG_(INFO) << "UnlinkCoreMockTest-end UnlinkCoreMockTest_DoUnlink_001"; +} + +/** + * @tc.name: UnlinkCoreMockTest_DoUnlink_002 + * @tc.desc: Test function of UnlinkCore::DoUnlink interface for FAILED. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(UnlinkCoreMockTest, UnlinkCoreMockTest_DoUnlink_002, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "UnlinkCoreMockTest-begin UnlinkCoreMockTest_DoUnlink_002"; + + EXPECT_CALL(*uvMock, uv_fs_unlink(_, _, _, _)).WillOnce(Return(-1)); + + string path = tempFilePath.string(); + auto res = UnlinkCore::DoUnlink(path); + EXPECT_EQ(res.IsSuccess(), false); + + GTEST_LOG_(INFO) << "UnlinkCoreMockTest-end UnlinkCoreMockTest_DoUnlink_002"; +} + +} // namespace OHOS::FileManagement::ModuleFileIO::Test \ No newline at end of file diff --git a/interfaces/test/unittest/js/mod_fs/properties/write_core_mock_test.cpp b/interfaces/test/unittest/js/mod_fs/properties/write_core_mock_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e16651fad8e2df9ddd2b1c8be011c3820808b48e --- /dev/null +++ b/interfaces/test/unittest/js/mod_fs/properties/write_core_mock_test.cpp @@ -0,0 +1,122 @@ +/* + * Copyright (C) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "write_core.h" +#include "uv_fs_mock.h" + +#include + +namespace OHOS::FileManagement::ModuleFileIO::Test { +using namespace testing; +using namespace testing::ext; +using namespace std; + +class WriteCoreMockTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); + static inline shared_ptr uvMock = nullptr; +}; + +void WriteCoreMockTest::SetUpTestCase(void) +{ + GTEST_LOG_(INFO) << "SetUpTestCase"; + uvMock = std::make_shared(); + Uvfs::ins = uvMock; +} + +void WriteCoreMockTest::TearDownTestCase(void) +{ + GTEST_LOG_(INFO) << "TearDownTestCase"; + Uvfs::ins = nullptr; + uvMock = nullptr; +} + +void WriteCoreMockTest::SetUp(void) +{ + GTEST_LOG_(INFO) << "SetUp"; +} + +void WriteCoreMockTest::TearDown(void) +{ + GTEST_LOG_(INFO) << "TearDown"; +} + +/** + * @tc.name: WriteCoreMockTest_DoWrite1_001 + * @tc.desc: Test function of WriteCore::DoWrite3 interface for FALSE. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(WriteCoreMockTest, WriteCoreMockTest_DoWrite1_001, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "WriteCoreMockTest-begin WriteCoreMockTest_DoWrite1_001"; + + int32_t fd = 1; + string buffer; + + EXPECT_CALL(*uvMock, uv_fs_write(_, _, _, _, _, _, _)).WillOnce(Return(-1)); + auto res = WriteCore::DoWrite(fd, buffer); + EXPECT_EQ(res.IsSuccess(), false); + + GTEST_LOG_(INFO) << "WriteCoreMockTest-end WriteCoreMockTest_DoWrite1_001"; +} + +/** + * @tc.name: WriteCoreMockTest_DoWrite1_002 + * @tc.desc: Test function of WriteCore::DoWrite3 interface for SUCCESS. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(WriteCoreMockTest, WriteCoreMockTest_DoWrite1_002, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "WriteCoreMockTest-begin WriteCoreMockTest_DoWrite1_002"; + + int32_t fd = 1; + string buffer; + + EXPECT_CALL(*uvMock, uv_fs_write(_, _, _, _, _, _, _)).WillOnce(Return(1)); + auto res = WriteCore::DoWrite(fd, buffer); + EXPECT_EQ(res.IsSuccess(), true); + + GTEST_LOG_(INFO) << "WriteCoreMockTest-end WriteCoreMockTest_DoWrite1_002"; +} + +/** + * @tc.name: WriteCoreMockTest_DoWrite2_003 + * @tc.desc: Test function of WriteCore::DoWrite2 interface for FALSE. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(WriteCoreMockTest, WriteCoreMockTest_DoWrite2_003, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "WriteCoreMockTest-begin WriteCoreMockTest_DoWrite2_003"; + + int32_t fd = -1; + string buffer; + + EXPECT_CALL(*uvMock, uv_fs_write(_, _, _, _, _, _, _)).WillOnce(Return(-1)); + auto res = WriteCore::DoWrite(fd, buffer); + EXPECT_EQ(res.IsSuccess(), false); + + GTEST_LOG_(INFO) << "WriteCoreMockTest-end WriteCoreMockTest_DoWrite2_003"; +} + +} // namespace OHOS::FileManagement::ModuleFileIO::Test \ No newline at end of file diff --git a/interfaces/test/unittest/js/mod_fs/properties/write_core_test.cpp b/interfaces/test/unittest/js/mod_fs/properties/write_core_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..1741f168f8781985786a0559a8b297b628df4402 --- /dev/null +++ b/interfaces/test/unittest/js/mod_fs/properties/write_core_test.cpp @@ -0,0 +1,148 @@ +/* + * Copyright (C) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "write_core.h" + +#include + +namespace OHOS::FileManagement::ModuleFileIO::Test { +using namespace testing; +using namespace testing::ext; +using namespace std; + +class WriteCoreTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); +}; + +void WriteCoreTest::SetUpTestCase(void) +{ + GTEST_LOG_(INFO) << "SetUpTestCase"; +} + +void WriteCoreTest::TearDownTestCase(void) +{ + GTEST_LOG_(INFO) << "TearDownTestCase"; +} + +void WriteCoreTest::SetUp(void) +{ + GTEST_LOG_(INFO) << "SetUp"; +} + +void WriteCoreTest::TearDown(void) +{ + GTEST_LOG_(INFO) << "TearDown"; +} + +/** + * @tc.name: WriteCoreTest_DoWrite1_001 + * @tc.desc: Test function of WriteCore::DoWrite1 interface for FALSE. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(WriteCoreTest, WriteCoreTest_DoWrite1_001, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "WriteCoreTest-begin WriteCoreTest_DoWrite1_001"; + int32_t fd = -1; + string buffer; + auto res = WriteCore::DoWrite(fd, buffer); + + EXPECT_EQ(res.IsSuccess(), false); + GTEST_LOG_(INFO) << "WriteCoreTest-end WriteCoreTest_DoWrite1_001"; +} + +/** + * @tc.name: WriteCoreTest_DoWrite2_001 + * @tc.desc: Test function of WriteCore::DoWrite2 interface for FALSE. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(WriteCoreTest, WriteCoreTest_DoWrite2_001, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "WriteCoreTest-begin WriteCoreTest_DoWrite2_001"; + int32_t fd = -1; + string buffer; + + auto res = WriteCore::DoWrite(fd, buffer); + EXPECT_EQ(res.IsSuccess(), false); + GTEST_LOG_(INFO) << "WriteCoreTest-end WriteCoreTest_DoWrite2_001"; +} + +#if defined(_WIN64) || defined(__X86_64__) || defined(__ppc64__) || defined(__LP64__) +/** + * @tc.name: WriteCoreTest_DoWrite1_002 + * @tc.desc: Test function of WriteCore::DoWrite1 interface for FALSE. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(WriteCoreTest, WriteCoreTest_DoWrite1_002, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "WriteCoreTest-begin WriteCoreTest_DoWrite1_002"; + int32_t fd = -1; + ArrayBuffer buffer(nullptr, 0); + + auto res = WriteCore::DoWrite(fd, buffer); + EXPECT_EQ(res.IsSuccess(), false); + GTEST_LOG_(INFO) << "WriteCoreTest-end WriteCoreTest_DoWrite1_002"; +} +#else +#endif + +/** + * @tc.name: WriteCoreTest_DoWrite1_003 + * @tc.desc: Test function of WriteCore::DoWrite1 interface for FALSE. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(WriteCoreTest, WriteCoreTest_DoWrite1_003, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "WriteCoreTest-begin WriteCoreTest_DoWrite1_003"; + int32_t fd = 1; + ArrayBuffer buffer(nullptr, 1); + std::optional options = std::make_optional(WriteOptions()); + options->offset = std::make_optional(-1); + + auto res = WriteCore::DoWrite(fd, buffer, options); + EXPECT_EQ(res.IsSuccess(), false); + GTEST_LOG_(INFO) << "WriteCoreTest-end WriteCoreTest_DoWrite1_003"; +} + +/** + * @tc.name: WriteCoreTest_DoWrite1_004 + * @tc.desc: Test function of WriteCore::DoWrite1 interface for FALSE. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(WriteCoreTest, WriteCoreTest_DoWrite1_004, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "WriteCoreTest-begin WriteCoreTest_DoWrite1_004"; + int32_t fd = 1; + ArrayBuffer buffer(nullptr, 1); + + auto res = WriteCore::DoWrite(fd, buffer); + EXPECT_EQ(res.IsSuccess(), false); + GTEST_LOG_(INFO) << "WriteCoreTest-end WriteCoreTest_DoWrite1_004"; +} + +} // namespace OHOS::FileManagement::ModuleFileIO::Test \ No newline at end of file diff --git a/interfaces/test/unittest/js/mod_hash/hash_core_test.cpp b/interfaces/test/unittest/js/mod_hash/hash_core_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..069a3230e9d756b9f4a145bbd6e918432ddfa557 --- /dev/null +++ b/interfaces/test/unittest/js/mod_hash/hash_core_test.cpp @@ -0,0 +1,136 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include +#include "hash_core.h" + +namespace OHOS { +namespace FileManagement { +namespace ModuleFileIO { +using namespace std; + +static const string g_filePath = "/data/test/HashCoreTest.txt"; +class HashCoreTest : public testing::Test { +public: + static void SetUpTestCase(void) + { + int32_t fd = open(g_filePath.c_str(), O_CREAT | O_RDWR, 0644); + close(fd); + }; + static void TearDownTestCase() + { + rmdir(g_filePath.c_str()); + }; + void SetUp() {}; + void TearDown() {}; +}; + +/** + * @tc.name: DoHashTest_0001 + * @tc.desc: Test function of DoHash() interface for invalid alg. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: AR000IGDNF + */ +HWTEST_F(HashCoreTest, DoHashTest_0001, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "HashCoreTest-begin DoHashTest_0001"; + string alg = "sha128"; + auto ret = HashCore::DoHash(g_filePath, alg); + EXPECT_FALSE(ret.IsSuccess()); + + auto err = ret.GetError(); + EXPECT_EQ(err.GetErrNo(), 13900020); + + GTEST_LOG_(INFO) << "HashCoreTest-end DoHashTest_0001"; +} + +/** + * @tc.name: DoHashTest_0002 + * @tc.desc: Test function of DoHash() interface for md5 success. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: AR000IGDNF + */ +HWTEST_F(HashCoreTest, DoHashTest_0002, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "HashCoreTest-begin DoHashTest_0002"; + auto ret = HashCore::DoHash(g_filePath, "md5"); + ASSERT_TRUE(ret.IsSuccess()); + + GTEST_LOG_(INFO) << "HashCoreTest-end DoHashTest_0002"; +} + +/** + * @tc.name: DoHashTest_0003 + * @tc.desc: Test function of DoHash() interface for sha1 success. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: AR000IGDNF + */ +HWTEST_F(HashCoreTest, DoHashTest_0003, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "HashCoreTest-begin DoHashTest_0003"; + auto ret = HashCore::DoHash(g_filePath, "sha1"); + ASSERT_TRUE(ret.IsSuccess()); + + GTEST_LOG_(INFO) << "HashCoreTest-end DoHashTest_0003"; +} + +/** + * @tc.name: DoHashTest_0004 + * @tc.desc: Test function of DoHash() interface for sha256 success. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: AR000IGDNF + */ +HWTEST_F(HashCoreTest, DoHashTest_0004, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "HashCoreTest-begin DoHashTest_0004"; + auto ret = HashCore::DoHash(g_filePath, "sha256"); + ASSERT_TRUE(ret.IsSuccess()); + + GTEST_LOG_(INFO) << "HashCoreTest-end DoHashTest_0004"; +} + +/** + * @tc.name: DoHashTest_0005 + * @tc.desc: Test function of DoHash() interface for no such file or directory. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: AR000IGDNF + */ +HWTEST_F(HashCoreTest, DoHashTest_0005, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "HashCoreTest-begin DoHashTest_0005"; + auto ret = HashCore::DoHash("/data/local/tmp/azuxyicayhyskjeh", "sha256"); + EXPECT_FALSE(ret.IsSuccess()); + + auto err = ret.GetError(); + EXPECT_EQ(err.GetErrNo(), 13900002); + + GTEST_LOG_(INFO) << "HashCoreTest-end DoHashTest_0005"; +} + +} // namespace ModuleFileIO +} // namespace FileManagement +} // namespace OHOS \ No newline at end of file diff --git a/interfaces/test/unittest/js/mod_securitylabel/securitylabel_core_test.cpp b/interfaces/test/unittest/js/mod_securitylabel/securitylabel_core_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f320af0371ac30c73381a072a2a449b71ebe3a99 --- /dev/null +++ b/interfaces/test/unittest/js/mod_securitylabel/securitylabel_core_test.cpp @@ -0,0 +1,144 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include +#include "securitylabel_core.h" + +namespace OHOS { +namespace FileManagement { +namespace ModuleSecurityLabel { +using namespace std; +using namespace OHOS::FileManagement::ModuleFileIO; + +static const string g_filePath = "/data/test/SecurityLabelCoreTest.txt"; +static const string g_validFilePath = "/data/test/validFilePath"; + +class SecurityLabelCoreTest : public testing::Test { +public: + static void SetUpTestCase(void) + { + int32_t fd = open(g_filePath.c_str(), O_CREAT | O_RDWR, 0644); + close(fd); + }; + static void TearDownTestCase() + { + rmdir(g_filePath.c_str()); + }; + void SetUp() {}; + void TearDown() {}; +}; + +/** + * @tc.name: DoSetSecurityLabel_0001 + * @tc.desc: Test function of DoSetSecurityLabel() interface for invalid level. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: AR000IGDNF + */ +HWTEST_F(SecurityLabelCoreTest, DoSetSecurityLabel_0001, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "SecurityLabelCoreTest-begin DoSetSecurityLabel_0001"; + auto ret = DoSetSecurityLabel(g_filePath, "abc"); + EXPECT_FALSE(ret.IsSuccess()); + + auto err = ret.GetError(); + EXPECT_EQ(err.GetErrNo(), 13900020); + + GTEST_LOG_(INFO) << "SecurityLabelCoreTest-end DoSetSecurityLabel_0001"; +} + +/** + * @tc.name: DoSetSecurityLabel_0002 + * @tc.desc: Test function of DoSetSecurityLabel() interface for invalid path. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: AR000IGDNF + */ +HWTEST_F(SecurityLabelCoreTest, DoSetSecurityLabel_0002, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "SecurityLabelCoreTest-begin DoSetSecurityLabel_0002"; + auto ret = DoSetSecurityLabel(g_validFilePath, "s1"); + EXPECT_FALSE(ret.IsSuccess()); + + auto err = ret.GetError(); + EXPECT_EQ(err.GetErrNo(), 13900002); + + GTEST_LOG_(INFO) << "SecurityLabelCoreTest-end DoSetSecurityLabel_0002"; +} + +/** + * @tc.name: DoSetSecurityLabel_0003 + * @tc.desc: Test function of DoSetSecurityLabel() interface for success. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: AR000IGDNF + */ +HWTEST_F(SecurityLabelCoreTest, DoSetSecurityLabel_0003, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "SecurityLabelCoreTest-begin DoSetSecurityLabel_0003"; + auto ret = DoSetSecurityLabel(g_filePath, "s2"); + ASSERT_TRUE(ret.IsSuccess()); + + GTEST_LOG_(INFO) << "SecurityLabelCoreTest-end DoSetSecurityLabel_0003"; +} + +/** + * @tc.name: DoGetSecurityLabel_0001 + * @tc.desc: Test function of DoGetSecurityLabel() interface for invalid path. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: AR000IGDNF + */ +HWTEST_F(SecurityLabelCoreTest, DoGetSecurityLabel_0001, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "SecurityLabelCoreTest-begin DoGetSecurityLabel_0001"; + auto ret = DoGetSecurityLabel(g_validFilePath); + EXPECT_TRUE(ret.IsSuccess()); + + const string level = ret.GetData().value(); + EXPECT_EQ(level, "s3"); + + GTEST_LOG_(INFO) << "SecurityLabelCoreTest-end DoGetSecurityLabel_0001"; +} + +/** + * @tc.name: DoGetSecurityLabel_0002 + * @tc.desc: Test function of DoGetSecurityLabel() interface for success. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: AR000IGDNF + */ +HWTEST_F(SecurityLabelCoreTest, DoGetSecurityLabel_0002, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "SecurityLabelCoreTest-begin DoGetSecurityLabel_0002"; + auto ret = DoGetSecurityLabel(g_filePath); + EXPECT_TRUE(ret.IsSuccess()); + + const string level = ret.GetData().value(); + EXPECT_EQ(level, "s2"); + + GTEST_LOG_(INFO) << "SecurityLabelCoreTest-end DoGetSecurityLabel_0002"; +} + +} // namespace ModuleSecurityLabel +} // namespace FileManagement +} // namespace OHOS \ No newline at end of file diff --git a/interfaces/test/unittest/remote_uri/BUILD.gn b/interfaces/test/unittest/remote_uri/BUILD.gn index 41788952a0ad984b286eb1e29eac139c24950b57..5b652a574417d5532285b758fdab9213f5127f77 100644 --- a/interfaces/test/unittest/remote_uri/BUILD.gn +++ b/interfaces/test/unittest/remote_uri/BUILD.gn @@ -1,4 +1,4 @@ -# Copyright (c) 2022-2023 Huawei Device Co., Ltd. +# Copyright (c) 2022-2025 Huawei Device Co., Ltd. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at @@ -26,16 +26,14 @@ ohos_unittest("remote_uri_test") { "${file_api_path}/interfaces/kits/native/remote_uri", ] - deps = [ - "${file_api_path}/interfaces/kits/native:remote_uri_native", - "//third_party/googletest:gtest_main", - ] + deps = [ "${file_api_path}/interfaces/kits/native:remote_uri_native" ] external_deps = [ "ability_base:zuri", "access_token:libaccesstoken_sdk", "c_utils:utils", "c_utils:utilsbase", + "googletest:gtest_main", "ipc:ipc_core", ] } diff --git a/interfaces/test/unittest/task_signal/BUILD.gn b/interfaces/test/unittest/task_signal/BUILD.gn index d4de828b534f282130715af73d7ead08aab27181..2f9900498e80121911e65beaa44b750ca51d02d5 100644 --- a/interfaces/test/unittest/task_signal/BUILD.gn +++ b/interfaces/test/unittest/task_signal/BUILD.gn @@ -1,4 +1,4 @@ -# Copyright (c) 2024 Huawei Device Co., Ltd. +# Copyright (c) 2024-2025 Huawei Device Co., Ltd. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at @@ -29,11 +29,11 @@ ohos_unittest("task_signal_test") { deps = [ "${file_api_path}/interfaces/kits/native:task_signal_native", "${utils_path}/filemgmt_libhilog:filemgmt_libhilog", - "//third_party/googletest:gtest_main", ] external_deps = [ "c_utils:utils", + "googletest:gtest_main", "hilog:libhilog", ] } diff --git a/utils/filemgmt_libfs/BUILD.gn b/utils/filemgmt_libfs/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..39bd586157bfa89fb951ac0308315a9126974afd --- /dev/null +++ b/utils/filemgmt_libfs/BUILD.gn @@ -0,0 +1,72 @@ +# Copyright (c) 2025 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/ohos.gni") +import("//foundation/filemanagement/file_api/file_api.gni") + +config("libfs_public_config") { + visibility = [ ":*" ] + + include_dirs = [ + "include", + "${utils_path}/common/include", + ] +} + +ohos_shared_library("filemgmt_libfs") { + cflags_cc = [ "-std=c++17" ] + if (!use_mingw_win && !use_mac) { + cflags = [ + "-fdata-sections", + "-ffunction-sections", + "-Oz", + ] + cflags_cc += [ + "-fvisibility-inlines-hidden", + "-Oz", + ] + branch_protector_ret = "pac_ret" + sanitize = { + integer_overflow = true + ubsan = true + boundary_sanitize = true + cfi = true + cfi_cross_dso = true + debug = false + } + } + + sources = [ "src/fs_error.cpp" ] + + if (use_mingw_win) { + defines = [ "WIN_PLATFORM" ] + } + if (use_mac) { + defines = [ "IOS_PLATFORM" ] + } + + public_configs = [ ":libfs_public_config" ] + + deps = [ "${utils_path}/filemgmt_libhilog:filemgmt_libhilog" ] + + external_deps = [ + "hilog:libhilog", + "libuv:uv", + ] + + use_exceptions = true + + subsystem_name = "filemanagement" + innerapi_tags = [ "platformsdk" ] + part_name = "file_api" +} diff --git a/utils/filemgmt_libfs/include/filemgmt_libfs.h b/utils/filemgmt_libfs/include/filemgmt_libfs.h new file mode 100644 index 0000000000000000000000000000000000000000..fb4209c6e1ae7c029c3fb822c3190a6dbf96e409 --- /dev/null +++ b/utils/filemgmt_libfs/include/filemgmt_libfs.h @@ -0,0 +1,23 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef UTILS_FILEMGMT_LIBFS_INCLUDE_FILEMGMT_LIBFS_H +#define UTILS_FILEMGMT_LIBFS_INCLUDE_FILEMGMT_LIBFS_H + +#include "fs_array_buffer.h" +#include "fs_error.h" +#include "fs_result.h" + +#endif // UTILS_FILEMGMT_LIBFS_INCLUDE_FILEMGMT_LIBFS_H diff --git a/utils/filemgmt_libfs/include/fs_array_buffer.h b/utils/filemgmt_libfs/include/fs_array_buffer.h new file mode 100644 index 0000000000000000000000000000000000000000..183743384792249a4265a5ca540c03246abd1104 --- /dev/null +++ b/utils/filemgmt_libfs/include/fs_array_buffer.h @@ -0,0 +1,31 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef UTILS_FILEMGMT_LIBFS_INCLUDE_FS_ARRAY_BUFFER_H +#define UTILS_FILEMGMT_LIBFS_INCLUDE_FS_ARRAY_BUFFER_H + +#include + +namespace OHOS::FileManagement::ModuleFileIO { + +struct ArrayBuffer { + void *buf; + size_t length; + + ArrayBuffer(void *buffer, size_t len) : buf(buffer), length(len) {} +}; + +} // namespace OHOS::FileManagement::ModuleFileIO +#endif // UTILS_FILEMGMT_LIBFS_INCLUDE_FS_ARRAY_BUFFER_H diff --git a/utils/filemgmt_libfs/include/fs_error.h b/utils/filemgmt_libfs/include/fs_error.h new file mode 100644 index 0000000000000000000000000000000000000000..53edb18978ac71919fd76bc72abcc2a82c792075 --- /dev/null +++ b/utils/filemgmt_libfs/include/fs_error.h @@ -0,0 +1,428 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef UTILS_FILEMGMT_LIBFS_INCLUDE_FS_ERROR_H +#define UTILS_FILEMGMT_LIBFS_INCLUDE_FS_ERROR_H + +#include +#include +#include +#include +#include + +namespace OHOS::FileManagement::ModuleFileIO { +using namespace std; + +#if (defined IOS_PLATFORM) || (defined WIN_PLATFORM) +constexpr int EBADR = 53; +constexpr int EBADFD = 77; +constexpr int ERESTART = 85; +#endif +#ifdef WIN_PLATFORM +constexpr int EDQUOT = 122; +#endif +constexpr int UNKNOWN_ERR = -1; +constexpr int NO_TASK_ERR = -2; +constexpr int CANCEL_ERR = -3; +constexpr int ERRNO_NOERR = 0; +constexpr int ECONNECTIONFAIL = 45; +constexpr int ECONNECTIONABORT = 46; +constexpr int STORAGE_SERVICE_SYS_CAP_TAG = 13600000; +constexpr int FILEIO_SYS_CAP_TAG = 13900000; +constexpr int USER_FILE_MANAGER_SYS_CAP_TAG = 14000000; +constexpr int USER_FILE_SERVICE_SYS_CAP_TAG = 14300000; +constexpr int DISTRIBUTEDFILE_SERVICE_SYS_CAP_TAG = 22400000; +constexpr int SOFTBUS_TRANS_FILE_PERMISSION_DENIED = -426114938; +constexpr int SOFTBUS_TRANS_FILE_DISK_QUOTA_EXCEEDED = -426114937; +constexpr int SOFTBUS_TRANS_FILE_NO_MEMORY = -426114936; +constexpr int SOFTBUS_TRANS_FILE_NETWORK_ERROR = -426114935; +constexpr int SOFTBUS_TRANS_FILE_NOT_FOUND = -426114934; +constexpr int SOFTBUS_TRANS_FILE_EXISTED = -426114933; +constexpr int DFS_CANCEL_SUCCESS = 204; +const std::string FILEIO_TAG_ERR_CODE = "code"; +const std::string FILEIO_TAG_ERR_DATA = "data"; + +enum ErrCodeSuffixOfFileIO { + E_PERM = 1, + E_NOENT, + E_SRCH, + E_INTR, + E_IO, + E_NXIO, + E_2BIG, + E_BADF, + E_CHILD, + E_AGAIN, + E_NOMEM, + E_ACCES, + E_FAULT, + E_BUSY, + E_EXIST, + E_XDEV, + E_NODEV, + E_NOTDIR, + E_ISDIR, + E_INVAL, + E_NFILE, + E_MFILE, + E_TXTBSY, + E_FBIG, + E_NOSPC, + E_SPIPE, + E_ROFS, + E_MLINK, + E_DEADLK, + E_NAMETOOLONG, + E_NOSYS, + E_NOTEMPTY, + E_LOOP, + E_WOULDBLOCK, + E_BADR, + E_NOSTR, + E_NODATA, + E_OVERFLOW, + E_BADFD, + E_RESTART, + E_DQUOT, + E_UKERR, + E_NOLCK, + E_NETUNREACH, + E_CONNECTION_FAIL, + E_CONNECTION_ABORT, + E_NOTASK, + E_UNCANCELED, + E_CANCELED, +}; + +enum ErrCodeSuffixOfUserFileManager { + E_DISPLAYNAME = 1, + E_URIM, + E_SUFFIX, + E_TRASH, + E_OPEN_MODE, + E_NOT_ALBUM, + E_ROOT_DIR, + E_MOVE_DENIED, + E_RENAME_DENIED, + E_RELATIVEPATH, + E_INNER_FAIL, + E_FILE_TYPE, + E_FILE_KEY, + E_INPUT +}; + +enum ErrCodeSuffixOfStorageService { + E_IPCSS = 1, + E_NOTSUPPORTEDFS, + E_MOUNT, + E_UNMOUNT, + E_VOLUMESTATE, + E_PREPARE, + E_DELETE, + E_NOOBJECT, + E_OUTOFRANGE +}; + +enum ErrCodeSuffixOfUserFileService { + E_IPCS = 1, + E_URIS, + E_GETINFO, + E_GETRESULT, + E_REGISTER, + E_REMOVE, + E_INIT, + E_NOTIFY, + E_CONNECT, + E_CALLBACK_AND_URI_HAS_NOT_RELATIONS, + E_CALLBACK_IS_NOT_REGISTER, + E_CAN_NOT_FIND_URI, + E_DO_NOT_HAVE_PARENT, + E_LOAD_SA, + E_COUNT +}; + +enum ErrCodeSuffixOfDistributedFile { + E_CLOUD_NOT_READY = 1, + E_NETWORK_ERR, + E_BATTERY_WARNING, + E_EXCEED_MAX_LIMIT, + E_DATABASE_FAILED +}; + +enum CommonErrCode { + E_PERMISSION = 201, + E_PERMISSION_SYS = 202, + E_PARAMS = 401, + E_DEVICENOTSUPPORT = 801, + E_OSNOTSUPPORT = 901, + E_UNKNOWN_ERROR = 13900042 +}; + +static inline std::unordered_map softbusErr2ErrCodeTable { + { SOFTBUS_TRANS_FILE_PERMISSION_DENIED, EPERM }, + { SOFTBUS_TRANS_FILE_DISK_QUOTA_EXCEEDED, EIO }, + { SOFTBUS_TRANS_FILE_NO_MEMORY, ENOMEM }, + { SOFTBUS_TRANS_FILE_NETWORK_ERROR, ENETUNREACH }, + { SOFTBUS_TRANS_FILE_NOT_FOUND, ENOENT }, + { SOFTBUS_TRANS_FILE_EXISTED, EEXIST }, + { DFS_CANCEL_SUCCESS, ECANCELED }, +}; + +static inline std::unordered_map uvCode2ErrCodeTable { + { "EPERM", EPERM }, + { "ENOENT", ENOENT }, + { "ESRCH", ESRCH }, + { "EINTR", EINTR }, + { "EIO", EIO }, + { "ENXIO", ENXIO }, + { "E2BIG", E2BIG }, + { "EBADF", EBADF }, + { "ECHILD", ECHILD }, + { "EAGAIN", EAGAIN }, + { "ENOMEM", ENOMEM }, + { "EACCES", EACCES }, + { "EFAULT", EFAULT }, + { "EBUSY", EBUSY }, + { "EEXIST", EEXIST }, + { "EXDEV", EXDEV }, + { "ENODEV", ENODEV }, + { "ENOTDIR", ENOTDIR }, + { "EISDIR", EISDIR }, + { "EINVAL", EINVAL }, + { "ENFILE", ENFILE }, + { "EMFILE", EMFILE }, + { "ETXTBSY", ETXTBSY }, + { "EFBIG", EFBIG }, + { "ENOSPC", ENOSPC }, + { "ESPIPE", ESPIPE }, + { "EROFS", EROFS }, + { "EMLINK", EMLINK }, + { "EDEADLK", EDEADLK }, + { "ENAMETOOLONG", ENAMETOOLONG }, + { "ENOSYS", ENOSYS }, + { "ENOTEMPTY", ENOTEMPTY }, + { "ELOOP", ELOOP }, + { "EWOULDBLOCK", EWOULDBLOCK }, + { "EBADR", EBADR }, + { "ENOSTR", ENOSTR }, + { "ENODATA", ENODATA }, + { "EOVERFLOW", EOVERFLOW }, + { "EBADFD", EBADFD }, + { "ERESTART", ERESTART }, + { "EDQUOT", EDQUOT }, + { "ENETUNREACH", ENETUNREACH }, + { "ECONNECTIONFAIL", ECONNECTIONFAIL }, + { "ECONNECTIONABORT", ECONNECTIONABORT }, + { "ECANCELED", ECANCELED }, +}; + +static inline std::unordered_map> errCodeTable { + { ERRNO_NOERR, { ERRNO_NOERR, "No error imformation" } }, + { EPERM, { FILEIO_SYS_CAP_TAG + E_PERM, "Operation not permitted" } }, + { ENOENT, { FILEIO_SYS_CAP_TAG + E_NOENT, "No such file or directory" } }, + { ESRCH, { FILEIO_SYS_CAP_TAG + E_SRCH, "No such process" } }, + { EINTR, { FILEIO_SYS_CAP_TAG + E_INTR, "Interrupted system call" } }, + { EIO, { FILEIO_SYS_CAP_TAG + E_IO, "I/O error" } }, + { ENXIO, { FILEIO_SYS_CAP_TAG + E_NXIO, "No such device or address" } }, + { E2BIG, { FILEIO_SYS_CAP_TAG + E_2BIG, "Arg list too long" } }, + { EBADF, { FILEIO_SYS_CAP_TAG + E_BADF, "Bad file descriptor" } }, + { ECHILD, { FILEIO_SYS_CAP_TAG + E_CHILD, "No child processes" } }, + { EAGAIN, { FILEIO_SYS_CAP_TAG + E_AGAIN, "Try again" } }, + { ENOMEM, { FILEIO_SYS_CAP_TAG + E_NOMEM, "Out of memory" } }, + { EACCES, { FILEIO_SYS_CAP_TAG + E_ACCES, "Permission denied" } }, + { EFAULT, { FILEIO_SYS_CAP_TAG + E_FAULT, "Bad address" } }, + { EBUSY, { FILEIO_SYS_CAP_TAG + E_BUSY, "Device or resource busy" } }, + { EEXIST, { FILEIO_SYS_CAP_TAG + E_EXIST, "File exists" } }, + { EXDEV, { FILEIO_SYS_CAP_TAG + E_XDEV, "Cross-device link" } }, + { ENODEV, { FILEIO_SYS_CAP_TAG + E_NODEV, "No such device" } }, + { ENOTDIR, { FILEIO_SYS_CAP_TAG + E_NOTDIR, "Not a directory" } }, + { EISDIR, { FILEIO_SYS_CAP_TAG + E_ISDIR, "Is a directory" } }, + { EINVAL, { FILEIO_SYS_CAP_TAG + E_INVAL, "Invalid argument" } }, + { ENFILE, { FILEIO_SYS_CAP_TAG + E_NFILE, "File table overflow" } }, + { EMFILE, { FILEIO_SYS_CAP_TAG + E_MFILE, "Too many open files" } }, + { ETXTBSY, { FILEIO_SYS_CAP_TAG + E_TXTBSY, "Text file busy" } }, + { EFBIG, { FILEIO_SYS_CAP_TAG + E_FBIG, "File too large" } }, + { ENOSPC, { FILEIO_SYS_CAP_TAG + E_NOSPC, "No space left on device" } }, + { ESPIPE, { FILEIO_SYS_CAP_TAG + E_SPIPE, "Illegal seek" } }, + { EROFS, { FILEIO_SYS_CAP_TAG + E_ROFS, "Read-only file system" } }, + { EMLINK, { FILEIO_SYS_CAP_TAG + E_MLINK, "Too many links" } }, + { EDEADLK, { FILEIO_SYS_CAP_TAG + E_DEADLK, "Resource deadlock would occur" } }, + { ENAMETOOLONG, { FILEIO_SYS_CAP_TAG + E_NAMETOOLONG, "File name too long" } }, + { ENOSYS, { FILEIO_SYS_CAP_TAG + E_NOSYS, "Function not implemented" } }, + { ENOTEMPTY, { FILEIO_SYS_CAP_TAG + E_NOTEMPTY, "Directory not empty" } }, + { ELOOP, { FILEIO_SYS_CAP_TAG + E_LOOP, "Too many symbolic links encountered" } }, + { EWOULDBLOCK, { FILEIO_SYS_CAP_TAG + E_WOULDBLOCK, "Operation would block" } }, + { EBADR, { FILEIO_SYS_CAP_TAG + E_BADR, "Invalid request descriptor" } }, + { ENOSTR, { FILEIO_SYS_CAP_TAG + E_NOSTR, "Device not a stream" } }, + { ENODATA, { FILEIO_SYS_CAP_TAG + E_NODATA, "No data available" } }, + { EOVERFLOW, { FILEIO_SYS_CAP_TAG + E_OVERFLOW, "Value too large for defined data type" } }, + { EBADFD, { FILEIO_SYS_CAP_TAG + E_BADFD, "File descriptor in bad state" } }, + { ERESTART, { FILEIO_SYS_CAP_TAG + E_RESTART, "Interrupted system call should be restarted" } }, + { EDQUOT, { FILEIO_SYS_CAP_TAG + E_DQUOT, "Quota exceeded" } }, + { UNKNOWN_ERR, { FILEIO_SYS_CAP_TAG + E_UKERR, "Unknown error" } }, + { ENOLCK, { FILEIO_SYS_CAP_TAG + E_NOLCK, "No record locks available" } }, + { ENETUNREACH, { FILEIO_SYS_CAP_TAG + E_NETUNREACH, "Network is unreachable" } }, + { ECONNECTIONFAIL, { FILEIO_SYS_CAP_TAG + E_CONNECTION_FAIL, "Connection failed" } }, + { ECONNECTIONABORT, { FILEIO_SYS_CAP_TAG + E_CONNECTION_ABORT, "Software caused connection abort" } }, + { NO_TASK_ERR, { FILEIO_SYS_CAP_TAG + E_NOTASK, "No task can be canceled" } }, + { CANCEL_ERR, { FILEIO_SYS_CAP_TAG + E_UNCANCELED, "Failed to cancel" } }, + { ECANCELED, { FILEIO_SYS_CAP_TAG + E_CANCELED, "Operation canceled" } }, + { FILEIO_SYS_CAP_TAG + E_PERM, { FILEIO_SYS_CAP_TAG + E_PERM, "Operation not permitted" } }, + { FILEIO_SYS_CAP_TAG + E_NOENT, { FILEIO_SYS_CAP_TAG + E_NOENT, "No such file or directory" } }, + { FILEIO_SYS_CAP_TAG + E_SRCH, { FILEIO_SYS_CAP_TAG + E_SRCH, "No such process" } }, + { FILEIO_SYS_CAP_TAG + E_INTR, { FILEIO_SYS_CAP_TAG + E_INTR, "Interrupted system call" } }, + { FILEIO_SYS_CAP_TAG + E_IO, { FILEIO_SYS_CAP_TAG + E_IO, "I/O error" } }, + { FILEIO_SYS_CAP_TAG + E_NXIO, { FILEIO_SYS_CAP_TAG + E_NXIO, "No such device or address" } }, + { FILEIO_SYS_CAP_TAG + E_2BIG, { FILEIO_SYS_CAP_TAG + E_2BIG, "Arg list too long" } }, + { FILEIO_SYS_CAP_TAG + E_BADF, { FILEIO_SYS_CAP_TAG + E_BADF, "Bad file descriptor" } }, + { FILEIO_SYS_CAP_TAG + E_CHILD, { FILEIO_SYS_CAP_TAG + E_CHILD, "No child processes" } }, + { FILEIO_SYS_CAP_TAG + E_AGAIN, { FILEIO_SYS_CAP_TAG + E_AGAIN, "Try again" } }, + { FILEIO_SYS_CAP_TAG + E_NOMEM, { FILEIO_SYS_CAP_TAG + E_NOMEM, "Out of memory" } }, + { FILEIO_SYS_CAP_TAG + E_ACCES, { FILEIO_SYS_CAP_TAG + E_ACCES, "Permission denied" } }, + { FILEIO_SYS_CAP_TAG + E_FAULT, { FILEIO_SYS_CAP_TAG + E_FAULT, "Bad address" } }, + { FILEIO_SYS_CAP_TAG + E_BUSY, { FILEIO_SYS_CAP_TAG + E_BUSY, "Device or resource busy" } }, + { FILEIO_SYS_CAP_TAG + E_EXIST, { FILEIO_SYS_CAP_TAG + E_EXIST, "File exists" } }, + { FILEIO_SYS_CAP_TAG + E_XDEV, { FILEIO_SYS_CAP_TAG + E_XDEV, "Cross-device link" } }, + { FILEIO_SYS_CAP_TAG + E_NODEV, { FILEIO_SYS_CAP_TAG + E_NODEV, "No such device" } }, + { FILEIO_SYS_CAP_TAG + E_NOTDIR, { FILEIO_SYS_CAP_TAG + E_NOTDIR, "Not a directory" } }, + { FILEIO_SYS_CAP_TAG + E_ISDIR, { FILEIO_SYS_CAP_TAG + E_ISDIR, "Is a directory" } }, + { FILEIO_SYS_CAP_TAG + E_INVAL, { FILEIO_SYS_CAP_TAG + E_INVAL, "Invalid argument" } }, + { FILEIO_SYS_CAP_TAG + E_NFILE, { FILEIO_SYS_CAP_TAG + E_NFILE, "File table overflow" } }, + { FILEIO_SYS_CAP_TAG + E_MFILE, { FILEIO_SYS_CAP_TAG + E_MFILE, "Too many open files" } }, + { FILEIO_SYS_CAP_TAG + E_TXTBSY, { FILEIO_SYS_CAP_TAG + E_TXTBSY, "Text file busy" } }, + { FILEIO_SYS_CAP_TAG + E_FBIG, { FILEIO_SYS_CAP_TAG + E_FBIG, "File too large" } }, + { FILEIO_SYS_CAP_TAG + E_NOSPC, { FILEIO_SYS_CAP_TAG + E_NOSPC, "No space left on device" } }, + { FILEIO_SYS_CAP_TAG + E_SPIPE, { FILEIO_SYS_CAP_TAG + E_SPIPE, "Illegal seek" } }, + { FILEIO_SYS_CAP_TAG + E_ROFS, { FILEIO_SYS_CAP_TAG + E_ROFS, "Read-only file system" } }, + { FILEIO_SYS_CAP_TAG + E_MLINK, { FILEIO_SYS_CAP_TAG + E_MLINK, "Too many links" } }, + { FILEIO_SYS_CAP_TAG + E_DEADLK, { FILEIO_SYS_CAP_TAG + E_DEADLK, "Resource deadlock would occur" } }, + { FILEIO_SYS_CAP_TAG + E_NAMETOOLONG, { FILEIO_SYS_CAP_TAG + E_NAMETOOLONG, "File name too long" } }, + { FILEIO_SYS_CAP_TAG + E_NOSYS, { FILEIO_SYS_CAP_TAG + E_NOSYS, "Function not implemented" } }, + { FILEIO_SYS_CAP_TAG + E_NOTEMPTY, { FILEIO_SYS_CAP_TAG + E_NOTEMPTY, "Directory not empty" } }, + { FILEIO_SYS_CAP_TAG + E_LOOP, { FILEIO_SYS_CAP_TAG + E_LOOP, "Too many symbolic links encountered" } }, + { FILEIO_SYS_CAP_TAG + E_WOULDBLOCK, { FILEIO_SYS_CAP_TAG + E_WOULDBLOCK, "Operation would block" } }, + { FILEIO_SYS_CAP_TAG + E_BADR, { FILEIO_SYS_CAP_TAG + E_BADR, "Invalid request descriptor" } }, + { FILEIO_SYS_CAP_TAG + E_NOSTR, { FILEIO_SYS_CAP_TAG + E_NOSTR, "Device not a stream" } }, + { FILEIO_SYS_CAP_TAG + E_NODATA, { FILEIO_SYS_CAP_TAG + E_NODATA, "No data available" } }, + { FILEIO_SYS_CAP_TAG + E_OVERFLOW, { FILEIO_SYS_CAP_TAG + E_OVERFLOW, "Value too large for defined data type" } }, + { FILEIO_SYS_CAP_TAG + E_BADFD, { FILEIO_SYS_CAP_TAG + E_BADFD, "File descriptor in bad state" } }, + { FILEIO_SYS_CAP_TAG + E_RESTART, + { FILEIO_SYS_CAP_TAG + E_RESTART, "Interrupted system call should be restarted" } }, + { FILEIO_SYS_CAP_TAG + E_DQUOT, { FILEIO_SYS_CAP_TAG + E_DQUOT, "Quota exceeded" } }, + { FILEIO_SYS_CAP_TAG + E_UKERR, { FILEIO_SYS_CAP_TAG + E_UKERR, "Unknown error" } }, + { FILEIO_SYS_CAP_TAG + E_NOLCK, { FILEIO_SYS_CAP_TAG + E_NOLCK, "No record locks available" } }, + { FILEIO_SYS_CAP_TAG + E_NETUNREACH, { FILEIO_SYS_CAP_TAG + E_NETUNREACH, "Network is unreachable" } }, + { FILEIO_SYS_CAP_TAG + E_CONNECTION_FAIL, { FILEIO_SYS_CAP_TAG + E_CONNECTION_FAIL, "Connection failed" } }, + { FILEIO_SYS_CAP_TAG + E_CONNECTION_ABORT, + { FILEIO_SYS_CAP_TAG + E_CONNECTION_ABORT, "Software caused connection abort" } }, + { USER_FILE_MANAGER_SYS_CAP_TAG + E_DISPLAYNAME, + { USER_FILE_MANAGER_SYS_CAP_TAG + E_DISPLAYNAME, "Invalid display name" } }, + { USER_FILE_MANAGER_SYS_CAP_TAG + E_URIM, { USER_FILE_MANAGER_SYS_CAP_TAG + E_URIM, "Invalid uri" } }, + { USER_FILE_MANAGER_SYS_CAP_TAG + E_SUFFIX, + { USER_FILE_MANAGER_SYS_CAP_TAG + E_SUFFIX, "Invalid file extension" } }, + { USER_FILE_MANAGER_SYS_CAP_TAG + E_TRASH, + { USER_FILE_MANAGER_SYS_CAP_TAG + E_TRASH, "File has been put into trash bin" } }, + { USER_FILE_MANAGER_SYS_CAP_TAG + E_OPEN_MODE, + { USER_FILE_MANAGER_SYS_CAP_TAG + E_OPEN_MODE, "Invalid open mode" } }, + { USER_FILE_MANAGER_SYS_CAP_TAG + E_NOT_ALBUM, + { USER_FILE_MANAGER_SYS_CAP_TAG + E_NOT_ALBUM, "The uri is not album" } }, + { USER_FILE_MANAGER_SYS_CAP_TAG + E_ROOT_DIR, { USER_FILE_MANAGER_SYS_CAP_TAG + E_ROOT_DIR, "Invalid root dir" } }, + { USER_FILE_MANAGER_SYS_CAP_TAG + E_MOVE_DENIED, + { USER_FILE_MANAGER_SYS_CAP_TAG + E_MOVE_DENIED, "Failed to move as dir check failed" } }, + { USER_FILE_MANAGER_SYS_CAP_TAG + E_RENAME_DENIED, + { USER_FILE_MANAGER_SYS_CAP_TAG + E_RENAME_DENIED, "Failed to rename as dir check failed" } }, + { USER_FILE_MANAGER_SYS_CAP_TAG + E_RELATIVEPATH, + { USER_FILE_MANAGER_SYS_CAP_TAG + E_RELATIVEPATH, "Relative path not exist or invalid" } }, + { USER_FILE_MANAGER_SYS_CAP_TAG + E_INNER_FAIL, + { USER_FILE_MANAGER_SYS_CAP_TAG + E_INNER_FAIL, "MediaLibrary inner fail" } }, + { USER_FILE_MANAGER_SYS_CAP_TAG + E_FILE_TYPE, + { USER_FILE_MANAGER_SYS_CAP_TAG + E_FILE_TYPE, "File type is not allow in the directory" } }, + { USER_FILE_MANAGER_SYS_CAP_TAG + E_FILE_KEY, { USER_FILE_MANAGER_SYS_CAP_TAG + E_FILE_KEY, "Member not exist" } }, + { USER_FILE_MANAGER_SYS_CAP_TAG + E_INPUT, { USER_FILE_MANAGER_SYS_CAP_TAG + E_INPUT, "Wrong input parameter" } }, + { STORAGE_SERVICE_SYS_CAP_TAG + E_IPCSS, { STORAGE_SERVICE_SYS_CAP_TAG + E_IPCSS, "IPC error" } }, + { STORAGE_SERVICE_SYS_CAP_TAG + E_NOTSUPPORTEDFS, + { STORAGE_SERVICE_SYS_CAP_TAG + E_NOTSUPPORTEDFS, "Not supported filesystem" } }, + { STORAGE_SERVICE_SYS_CAP_TAG + E_MOUNT, { STORAGE_SERVICE_SYS_CAP_TAG + E_MOUNT, "Failed to mount" } }, + { STORAGE_SERVICE_SYS_CAP_TAG + E_UNMOUNT, { STORAGE_SERVICE_SYS_CAP_TAG + E_UNMOUNT, "Failed to unmount" } }, + { STORAGE_SERVICE_SYS_CAP_TAG + E_VOLUMESTATE, + { STORAGE_SERVICE_SYS_CAP_TAG + E_VOLUMESTATE, "Incorrect volume state" } }, + { STORAGE_SERVICE_SYS_CAP_TAG + E_PREPARE, + { STORAGE_SERVICE_SYS_CAP_TAG + E_PREPARE, "Prepare directory or node error" } }, + { STORAGE_SERVICE_SYS_CAP_TAG + E_DELETE, + { STORAGE_SERVICE_SYS_CAP_TAG + E_DELETE, "Delete directory or node error" } }, + { STORAGE_SERVICE_SYS_CAP_TAG + E_NOOBJECT, { STORAGE_SERVICE_SYS_CAP_TAG + E_NOOBJECT, "No such object" } }, + { STORAGE_SERVICE_SYS_CAP_TAG + E_OUTOFRANGE, + { STORAGE_SERVICE_SYS_CAP_TAG + E_OUTOFRANGE, "User id out of range" } }, + { STORAGE_SERVICE_SYS_CAP_TAG + E_NOOBJECT, { STORAGE_SERVICE_SYS_CAP_TAG + E_NOOBJECT, "No such object" } }, + { USER_FILE_SERVICE_SYS_CAP_TAG + E_IPCS, { USER_FILE_SERVICE_SYS_CAP_TAG + E_IPCS, "IPC error" } }, + { USER_FILE_SERVICE_SYS_CAP_TAG + E_URIS, { USER_FILE_SERVICE_SYS_CAP_TAG + E_URIS, "Invalid uri" } }, + { USER_FILE_SERVICE_SYS_CAP_TAG + E_GETINFO, + { USER_FILE_SERVICE_SYS_CAP_TAG + E_GETINFO, "Fail to get fileextension info" } }, + { USER_FILE_SERVICE_SYS_CAP_TAG + E_GETRESULT, + { USER_FILE_SERVICE_SYS_CAP_TAG + E_GETRESULT, "Get wrong result" } }, + { USER_FILE_SERVICE_SYS_CAP_TAG + E_REGISTER, + { USER_FILE_SERVICE_SYS_CAP_TAG + E_REGISTER, "Fail to register notification" } }, + { USER_FILE_SERVICE_SYS_CAP_TAG + E_REMOVE, + { USER_FILE_SERVICE_SYS_CAP_TAG + E_REMOVE, "Fail to remove notification" } }, + { USER_FILE_SERVICE_SYS_CAP_TAG + E_INIT, + { USER_FILE_SERVICE_SYS_CAP_TAG + E_INIT, "Fail to init notification agent" } }, + { USER_FILE_SERVICE_SYS_CAP_TAG + E_NOTIFY, { USER_FILE_SERVICE_SYS_CAP_TAG + E_NOTIFY, "Fail to notify agent" } }, + { USER_FILE_SERVICE_SYS_CAP_TAG + E_CONNECT, + { USER_FILE_SERVICE_SYS_CAP_TAG + E_CONNECT, "Fail to connect file access extension ability" } }, + { USER_FILE_SERVICE_SYS_CAP_TAG + E_CALLBACK_AND_URI_HAS_NOT_RELATIONS, + { USER_FILE_SERVICE_SYS_CAP_TAG + E_CALLBACK_AND_URI_HAS_NOT_RELATIONS, + "The uri has no relationship with the callback and cannot be unregistered" } }, + { USER_FILE_SERVICE_SYS_CAP_TAG + E_CALLBACK_IS_NOT_REGISTER, + { USER_FILE_SERVICE_SYS_CAP_TAG + E_CALLBACK_IS_NOT_REGISTER, + "Cannot unregister the callback that has not been registered" } }, + { USER_FILE_SERVICE_SYS_CAP_TAG + E_CAN_NOT_FIND_URI, + { USER_FILE_SERVICE_SYS_CAP_TAG + E_CAN_NOT_FIND_URI, "Can not find registered uri" } }, + { USER_FILE_SERVICE_SYS_CAP_TAG + E_DO_NOT_HAVE_PARENT, + { USER_FILE_SERVICE_SYS_CAP_TAG + E_DO_NOT_HAVE_PARENT, "Do not have parent uri" } }, + { USER_FILE_SERVICE_SYS_CAP_TAG + E_LOAD_SA, + { USER_FILE_SERVICE_SYS_CAP_TAG + E_LOAD_SA, "Fail to load system ability" } }, + { USER_FILE_SERVICE_SYS_CAP_TAG + E_COUNT, { USER_FILE_SERVICE_SYS_CAP_TAG + E_COUNT, "Too many records" } }, + { E_PERMISSION, { E_PERMISSION, "Permission verification failed" } }, + { E_PERMISSION_SYS, { E_PERMISSION_SYS, "The caller is not a system application" } }, + { E_PARAMS, { E_PARAMS, "The input parameter is invalid" } }, + { E_DEVICENOTSUPPORT, { E_DEVICENOTSUPPORT, "The device doesn't support this api" } }, + { E_OSNOTSUPPORT, { E_OSNOTSUPPORT, "The os doesn't support this api" } }, + { DISTRIBUTEDFILE_SERVICE_SYS_CAP_TAG + E_CLOUD_NOT_READY, + { DISTRIBUTEDFILE_SERVICE_SYS_CAP_TAG + E_CLOUD_NOT_READY, "Cloud status not ready" } }, + { DISTRIBUTEDFILE_SERVICE_SYS_CAP_TAG + E_NETWORK_ERR, + { DISTRIBUTEDFILE_SERVICE_SYS_CAP_TAG + E_NETWORK_ERR, "Network unavailable" } }, + { DISTRIBUTEDFILE_SERVICE_SYS_CAP_TAG + E_BATTERY_WARNING, + { DISTRIBUTEDFILE_SERVICE_SYS_CAP_TAG + E_BATTERY_WARNING, "Battery level warning" } }, + { DISTRIBUTEDFILE_SERVICE_SYS_CAP_TAG + E_EXCEED_MAX_LIMIT, + { DISTRIBUTEDFILE_SERVICE_SYS_CAP_TAG + E_EXCEED_MAX_LIMIT, "Exceed the maximum limit" } }, + { DISTRIBUTEDFILE_SERVICE_SYS_CAP_TAG + E_DATABASE_FAILED, + { DISTRIBUTEDFILE_SERVICE_SYS_CAP_TAG + E_DATABASE_FAILED, "Database operation failed" } }, +}; + +class FsError { +public: + FsError(int errCode); + int GetErrNo() const; + const std::string &GetErrMsg() const; + ~FsError() = default; + explicit operator bool() const; + +private: + int errno_ = ERRNO_NOERR; + std::string errMsg_; +}; + +} // namespace OHOS::FileManagement::ModuleFileIO +#endif // UTILS_FILEMGMT_LIBFS_INCLUDE_FS_ERROR_H diff --git a/utils/filemgmt_libfs/include/fs_result.h b/utils/filemgmt_libfs/include/fs_result.h new file mode 100644 index 0000000000000000000000000000000000000000..12675c94917201ca92a4e61c6a5173ab8703d477 --- /dev/null +++ b/utils/filemgmt_libfs/include/fs_result.h @@ -0,0 +1,148 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef UTILS_FILEMGMT_LIBFS_INCLUDE_FS_RESULT_H +#define UTILS_FILEMGMT_LIBFS_INCLUDE_FS_RESULT_H + +#include "fs_error.h" + +#include +#include +#include +#include + +namespace OHOS::FileManagement::ModuleFileIO { + +template +class FsResult { + using OptionalData = std::optional; + +public: + static FsResult Success() + { + return FsResult(FsError(ERRNO_NOERR), std::nullopt); + } + + static FsResult Success(const T &data) + { + return FsResult(FsError(ERRNO_NOERR), std::make_optional(data)); + } + + static FsResult Success(T &&data) + { + return FsResult(FsError(ERRNO_NOERR), std::make_optional(std::move(data))); + } + + template , int> = 0> + static FsResult Success(const char *data) + { + return FsResult(FsError(ERRNO_NOERR), std::make_optional(std::string(data))); + } + + static FsResult Error(const int32_t code) + { + return FsResult(FsError(code), std::nullopt); + } + + bool IsSuccess() const + { + return !error_; + } + + const OptionalData &GetData() const + { + return data_; + } + + OptionalData &GetData() + { + return data_; + } + + const FsError &GetError() const + { + return error_; + } + + FsResult(const FsResult &) = delete; + FsResult &operator=(const FsResult &) = delete; + + FsResult(FsResult &&other) noexcept : error_(std::move(other.error_)), data_(std::move(other.data_)) {} + + FsResult &operator=(FsResult &&other) noexcept + { + if (this != &other) { + error_ = std::move(other.error_); + data_ = std::move(other.data_); + } + return *this; + } + + ~FsResult() = default; + +private: + FsError error_; + OptionalData data_; + + FsResult(const FsError &err, const OptionalData &data) : error_(err), data_(data) {} + + FsResult(const FsError &err, OptionalData &&data) : error_(err), data_(std::move(data)) {} +}; + +template <> +class FsResult { +private: + FsError error_; + explicit FsResult(const FsError &err) : error_(err) {} + +public: + static FsResult Success() + { + return FsResult(FsError(ERRNO_NOERR)); + } + + static FsResult Error(const int32_t code) + { + return FsResult(FsError(code)); + } + + bool IsSuccess() const + { + return !error_; + } + + const FsError &GetError() const + { + return error_; + } + + FsResult(const FsResult &) = delete; + FsResult &operator=(const FsResult &) = delete; + + FsResult(FsResult &&other) noexcept : error_(std::move(other.error_)) {} + + FsResult &operator=(FsResult &&other) noexcept + { + if (this != &other) { + error_ = std::move(other.error_); + } + return *this; + } + + ~FsResult() = default; +}; + +} // namespace OHOS::FileManagement::ModuleFileIO +#endif // UTILS_FILEMGMT_LIBFS_INCLUDE_FS_RESULT_H diff --git a/utils/filemgmt_libfs/src/fs_error.cpp b/utils/filemgmt_libfs/src/fs_error.cpp new file mode 100644 index 0000000000000000000000000000000000000000..3636a7d5f966a4633f5f57b73d7d705af0196de5 --- /dev/null +++ b/utils/filemgmt_libfs/src/fs_error.cpp @@ -0,0 +1,62 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "fs_error.h" +#include "uv.h" + +namespace OHOS::FileManagement::ModuleFileIO { +using namespace std; + +static int ConvertUVCode2ErrCode(int errCode) +{ + if (errCode >= 0) { + return errCode; + } + auto uvCode = string_view(uv_err_name(errCode)); + if (uvCode2ErrCodeTable.find(uvCode) != uvCode2ErrCodeTable.end()) { + return uvCode2ErrCodeTable.at(uvCode); + } + return UNKNOWN_ERR; +} + +FsError::FsError(int errCode) +{ + int genericCode = ConvertUVCode2ErrCode(errCode); + auto it = errCodeTable.find(genericCode); + if (it != errCodeTable.end()) { + errno_ = it->second.first; + errMsg_ = it->second.second; + } else { + errno_ = errCodeTable.at(UNKNOWN_ERR).first; + errMsg_ = errCodeTable.at(UNKNOWN_ERR).second + ", errno is " + to_string(abs(errCode)); + } +} + +int FsError::GetErrNo() const +{ + return errno_; +} + +const std::string &FsError::GetErrMsg() const +{ + return errMsg_; +} + +FsError::operator bool() const +{ + return errno_ != ERRNO_NOERR; +} + +} // namespace OHOS::FileManagement::ModuleFileIO