Debian Codegraph @

src/gengine/FsPath.cpp

raw
1 /*
2 * Copyright (C) 2004 Ivo Danihelka ([email protected])
3 *
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 2 of the License, or
7 * (at your option) any later version.
8 */
9 #include "FsPath.h"
10
11 #include "Log.h"
12 #include "PathException.h"
13
14 #include <string.h>
15 #include <errno.h>
16 #include <sys/stat.h>
17 #include <sys/types.h>
18 #include <unistd.h>
19
20 //-----------------------------------------------------------------
21 /**
22 * Get native filename.
23 * @param file posix filename
24 */
25 std::string
26 FsPath::getNative(const std::string &file)
27 {
28 return file;
29 }
30 //-----------------------------------------------------------------
31 /**
32 * Returns true when file or directory exists.
33 * @param file posix filename
34 */
35 bool
36 FsPath::exists(const std::string &file)
37 {
38 if (file.empty()) {
39 return true;
40 }
41
42 struct stat buf;
43 int error = stat(file.c_str(), &buf);
44 return !error;
45 }
46 //-----------------------------------------------------------------
47 /**
48 * Joint two paths.
49 * @param dir posix filename
50 * @param file posix filename
51 * @return "dir/file"
52 */
53 std::string
54 FsPath::join(const std::string &dir, const std::string &file)
55 {
56 if (dir.empty()) {
57 return file;
58 }
59
60 return dir + '/' + file;
61 }
62
63 //-----------------------------------------------------------------
64 /**
65 * Return path without file basename.
66 * @param file posix filename
67 */
68 inline std::string
69 dirPath(const std::string &file)
70 {
71 std::string dirs = "";
72 std::string::size_type pos = file.rfind('/');
73 if (pos == 0) {
74 //NOTE: root
75 dirs = "/";
76 }
77 else if (pos != std::string::npos) {
78 dirs = file.substr(0, pos);
79 }
80
81 return dirs;
82 }
83 //-----------------------------------------------------------------
84 /**
85 * Create dir.
86 * @param dir posix filename
87 * @throws NameException when error occurs
88 */
89 inline void
90 createDir(const std::string &dir)
91 {
92 if (dir.empty()) {
93 return;
94 }
95
96 #ifdef WIN32
97 int error = mkdir(dir.c_str());
98 #else
99 int error = mkdir(dir.c_str(), 0777);
100 #endif
101 if (error) {
102 throw PathException(ExInfo("cannot create dir")
103 .addInfo("stderror", strerror(errno))
104 .addInfo("dir", dir));
105 }
106 }
107 //-----------------------------------------------------------------
108 /**
109 * Create all directories in path (like "mkdir -p").
110 * @param file posix filename
111 */
112 void
113 FsPath::createPath(const std::string &file)
114 {
115 std::string parent = dirPath(file);
116 if (!FsPath::exists(parent)) {
117 createPath(parent);
118 createDir(parent);
119 }
120 }
121