]> git.tdb.fi Git - libs/core.git/blob - source/utils.cpp
Refactor the API
[libs/core.git] / source / utils.cpp
1 /* $Id$
2
3 This file is part of libmspfs
4 Copyright © 2006-2008  Mikko Rasa, Mikkosoft Productions
5 Distributed under the LGPL
6 */
7
8 #include <cerrno>
9 #include <msp/core/except.h>
10 #ifndef WIN32
11 #include <fnmatch.h>
12 #else
13 #include <msp/strings/glob.h>
14 #endif
15 #include <msp/strings/utils.h>
16 #include "dir.h"
17 #include "path.h"
18 #include "utils.h"
19
20 using namespace std;
21
22 namespace Msp {
23 namespace FS {
24
25 string basename(const Path &p)
26 {
27         return p[-1];
28 }
29
30 Path dirname(const Path &p)
31 {
32         return p.subpath(0, p.size()-1);
33 }
34
35 string basepart(const string &fn)
36 {
37         unsigned dot=fn.rfind('.');
38         return fn.substr(0, dot);
39 }
40
41 string extpart(const string &fn)
42 {
43         unsigned dot=fn.rfind('.');
44         if(dot==string::npos)
45                 return string();
46         return fn.substr(dot);
47 }
48
49 Path fix_case(const Path &path)
50 {
51         bool found=true;
52         Path result;
53         for(Path::Iterator i=path.begin(); i!=path.end(); ++i)
54         {
55                 if(!found || *i=="/")
56                         result/=*i;
57                 else
58                 {
59                         list<string> files;
60                         if(result.size())
61                                 files=list_files(result);
62                         else
63                                 files=list_files(".");
64
65                         found=false;
66                         for(list<string>::iterator j=files.begin(); (j!=files.end() && !found); ++j)
67                                 if(!strcasecmp(*j,*i))
68                                 {
69                                         result/=*j;
70                                         found=true;
71                                 }
72
73                         if(!found)
74                                 result/=*i;
75                 }
76         }
77
78         return result;
79 }
80
81 void unlink(const Path &path)
82 {
83         if(::unlink(path.str().c_str())==-1)
84                 throw SystemError("unlink failed", errno);
85 }
86
87 Path relative(const Path &path, const Path &base)
88 {
89         Path::Iterator i=path.begin();
90         Path::Iterator j=base.begin();
91         for(; (i!=path.end() && j!=base.end() && *i==*j); ++i, ++j) ;
92
93         Path result;
94         for(; j!=base.end(); ++j)
95                 result/="..";
96         for(; i!=path.end(); ++i)
97                 result/=*i;
98
99         return result;
100 }
101
102 } // namespace FS
103 } // namespace Msp