Massive copyright update. I'm sorry if I'm crediting Matze for something he didn...
[supertux.git] / src / file_system.cpp
1 //  $Id$
2 //
3 //  SuperTux
4 //  Copyright (C) 2006 Matthias Braun <matze@braunis.de>
5 //
6 //  This program is free software; you can redistribute it and/or
7 //  modify it under the terms of the GNU General Public License
8 //  as published by the Free Software Foundation; either version 2
9 //  of the License, or (at your option) any later version.
10 //
11 //  This program is distributed in the hope that it will be useful,
12 //  but WITHOUT ANY WARRANTY; without even the implied warranty of
13 //  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 //  GNU General Public License for more details.
15 //
16 //  You should have received a copy of the GNU General Public License
17 //  along with this program; if not, write to the Free Software
18 //  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
19
20 #include <config.h>
21
22 #include "log.hpp"
23 #include "file_system.hpp"
24
25 #include <string>
26 #include <vector>
27 #include <sstream>
28
29 namespace FileSystem
30 {
31
32 std::string dirname(const std::string& filename)
33 {
34   std::string::size_type p = filename.find_last_of('/');
35   if(p == std::string::npos)                              
36     return "";
37   
38   return filename.substr(0, p+1);
39 }
40
41 std::string basename(const std::string& filename)
42 {
43   std::string::size_type p = filename.find_last_of('/');
44   if(p == std::string::npos)
45     return filename;
46
47   return filename.substr(p+1, filename.size()-p-1);
48 }
49
50 std::string normalize(const std::string& filename)
51 {
52   std::vector<std::string> path_stack;
53
54   const char* p = filename.c_str();
55
56   while(true) {
57     while(*p == '/') {
58       p++;
59       continue;
60     }
61
62     const char* pstart = p;
63     while(*p != '/' && *p != 0) {
64       ++p;
65     }
66
67     size_t len = p - pstart;
68     if(len == 0)
69       break;
70     
71     std::string pathelem(pstart, p-pstart);
72     if(pathelem == ".")
73       continue;
74     
75     if(pathelem == "..") {
76       if(path_stack.empty()) {
77
78         log_warning << "Invalid '..' in path '" << filename << "'" << std::endl;
79         // push it into the result path so that the users sees his error...
80         path_stack.push_back(pathelem);
81       } else {
82         path_stack.pop_back();
83       }
84     } else {
85       path_stack.push_back(pathelem);
86     }
87   }
88
89   // construct path
90   std::ostringstream result;
91   for(std::vector<std::string>::iterator i = path_stack.begin();
92       i != path_stack.end(); ++i) {
93     result << '/' << *i;
94   }
95   if(path_stack.empty())
96     result << '/';
97
98   return result.str();
99 }
100
101 }
102