Initialize Tizen 2.3
[framework/web/wrt-plugins-common.git] / src_mobile / modules / tizen / Filesystem / Utils.cpp
1 /*
2  * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
3  *
4  *    Licensed under the Apache License, Version 2.0 (the "License");
5  *    you may not use this file except in compliance with the License.
6  *    You may obtain a copy of the License at
7  *
8  *        http://www.apache.org/licenses/LICENSE-2.0
9  *
10  *    Unless required by applicable law or agreed to in writing, software
11  *    distributed under the License is distributed on an "AS IS" BASIS,
12  *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  *    See the License for the specific language governing permissions and
14  *    limitations under the License.
15  */
16 /**
17  * @file    Utils.cpp
18  * @author  Zbigniew Kostrzewa (z.kostrzewa@samsung.com)
19  * @version 1.0
20  */
21
22 #include <sys/stat.h>
23 #include <cerrno>
24 #include <cstring>
25 #include <cstdlib>
26 #include <unistd.h>
27 #include <Commons/Exception.h>
28 #include "Utils.h"
29
30 namespace {
31 int try_mkdir(const char* path,
32               mode_t mode)
33 {
34     struct stat st;
35     int err = 0;
36
37     if (::stat(path, &st) != 0) {
38         if (::mkdir(path, mode) != 0) {
39             err = -1;
40         }
41     } else if (!S_ISDIR(st.st_mode)) {
42         errno = ENOTDIR;
43         err = -1;
44     }
45
46     return err;
47 }
48
49 int mkpath(const char* path,
50            mode_t mode)
51 {
52     char* copy = ::strdup(path);
53     if (NULL == copy) {
54         return -1;
55     }
56
57     int err = 0;
58     char* ptr = copy;
59     char* slash = NULL;
60
61     while ((0 == err) && (NULL != (slash = ::strchr(ptr, '/')))) {
62         if (slash != ptr) {
63             *slash = '\0';
64             err = try_mkdir(copy, mode);
65             *slash = '/';
66         }
67         ptr = slash + 1;
68     }
69
70     if (0 == err) {
71         err = try_mkdir(path, mode);
72     }
73
74     ::free(copy);
75     return err;
76 }
77 }
78
79 namespace WrtDeviceApis {
80 namespace Filesystem {
81 bool nodeExists(const std::string& path)
82 {
83     struct stat info;
84     if (stat(path.c_str(), &info) == 0) {
85         if (S_ISDIR(info.st_mode)) {
86             return true;
87         }
88     }
89     return false;
90 }
91
92 void makePath(const std::string& path,
93               mode_t mode)
94 {
95     if (mkpath(path.c_str(), mode) == -1) {
96         ThrowMsg(Commons::PlatformException, "Couldn't create path: " << path);
97     }
98 }
99 }
100 }