1 /*
2 * Copyright (c) 2023 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15 #include "utimes.h"
16
17 #include <unistd.h>
18
19 #include "common_func.h"
20 #include "file_utils.h"
21 #include "filemgmt_libhilog.h"
22
23 namespace OHOS {
24 namespace FileManagement {
25 namespace ModuleFileIO {
26 using namespace std;
27 using namespace OHOS::FileManagement::LibN;
28
Sync(napi_env env,napi_callback_info info)29 napi_value Utimes::Sync(napi_env env, napi_callback_info info)
30 {
31 NFuncArg funcArg(env, info);
32 if (!funcArg.InitArgs(NARG_CNT::TWO)) {
33 HILOGE("Number of arguments unmatched");
34 NError(EINVAL).ThrowErr(env);
35 return nullptr;
36 }
37
38 auto [succGetPath, path, ignore] = NVal(env, funcArg[NARG_POS::FIRST]).ToUTF8StringPath();
39 if (!succGetPath) {
40 HILOGE("Invalid path from JS first argument");
41 NError(EINVAL).ThrowErr(env);
42 return nullptr;
43 }
44
45 auto [succGetMtime, mtime] = NVal(env, funcArg[NARG_POS::SECOND]).ToDouble();
46 if (!succGetMtime || mtime < 0) {
47 HILOGE("Invalid mtime from JS second argument");
48 NError(EINVAL).ThrowErr(env);
49 return nullptr;
50 }
51
52 std::unique_ptr<uv_fs_t, decltype(CommonFunc::fs_req_cleanup)*> stat_req = {
53 new (std::nothrow) uv_fs_t, CommonFunc::fs_req_cleanup };
54 if (!stat_req) {
55 HILOGE("Failed to request heap memory.");
56 NError(ENOMEM).ThrowErr(env);
57 return nullptr;
58 }
59
60 int ret = uv_fs_stat(nullptr, stat_req.get(), path.get(), nullptr);
61 if (ret < 0) {
62 HILOGE("Failed to get stat of the file by path");
63 NError(ret).ThrowErr(env);
64 return nullptr;
65 }
66
67 std::unique_ptr<uv_fs_t, decltype(CommonFunc::fs_req_cleanup)*> utimes_req = {
68 new uv_fs_t, CommonFunc::fs_req_cleanup };
69 if (!utimes_req) {
70 HILOGE("Failed to request heap memory.");
71 NError(ENOMEM).ThrowErr(env);
72 return nullptr;
73 }
74
75 double atime = static_cast<double>(stat_req->statbuf.st_atim.tv_sec) +
76 static_cast<double>(stat_req->statbuf.st_atim.tv_nsec) / NS;
77 ret = uv_fs_utime(nullptr, utimes_req.get(), path.get(), atime, mtime / MS, nullptr);
78 if (ret < 0) {
79 HILOGE("Failed to chang mtime of the file for %{public}d", ret);
80 NError(ret).ThrowErr(env);
81 return nullptr;
82 }
83
84 return NVal::CreateUndefined(env).val_;
85 }
86
87 } // ModuleFileIO
88 } // FileManagement
89 } // OHOS