• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 
16 //! This file implement the file operations.
17 
18 use std::{fs, path::Path};
19 
20 use asset_definition::{log_throw_error, ErrCode, Result};
21 use asset_log::logi;
22 
23 const ROOT_PATH: &str = "data/service/el1/public/asset_service";
24 
construct_user_path(user_id: i32) -> String25 fn construct_user_path(user_id: i32) -> String {
26     format!("{}/{}", ROOT_PATH, user_id)
27 }
28 
29 /// Check user db dir exist.
is_user_db_dir_exist(user_id: i32) -> bool30 pub fn is_user_db_dir_exist(user_id: i32) -> bool {
31     let path_str = construct_user_path(user_id);
32     let path: &Path = Path::new(&path_str);
33     path.exists()
34 }
35 
36 /// Create user database directory.
create_user_db_dir(user_id: i32) -> Result<()>37 pub fn create_user_db_dir(user_id: i32) -> Result<()> {
38     if is_user_db_dir_exist(user_id) {
39         return Ok(());
40     }
41 
42     logi!("[INFO]Directory is not exist, create it...");
43     let path_str = construct_user_path(user_id);
44     let path: &Path = Path::new(&path_str);
45     match fs::create_dir(path) {
46         Ok(_) => Ok(()),
47         Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => Ok(()),
48         Err(e) => {
49             log_throw_error!(ErrCode::FileOperationError, "[FATAL][SA]Create dir failed! error is [{}]", e)
50         },
51     }
52 }
53 
54 /// Delete user database directory.
delete_user_db_dir(user_id: i32) -> Result<()>55 pub fn delete_user_db_dir(user_id: i32) -> Result<()> {
56     if !is_user_db_dir_exist(user_id) {
57         return Ok(());
58     }
59 
60     let path_str = construct_user_path(user_id);
61     let path: &Path = Path::new(&path_str);
62     match fs::remove_dir_all(path) {
63         Ok(_) => Ok(()),
64         Err(e) if e.kind() != std::io::ErrorKind::NotFound => Ok(()),
65         Err(e) => {
66             log_throw_error!(ErrCode::FileOperationError, "[FATAL][SA]Delete dir failed! error is [{}]", e)
67         },
68     }
69 }
70