Fix problems with overlong directory names: phase #1
[mono.git] / mcs / class / Mono.Posix / Mono.Unix / UnixPath.cs
1 //
2 // Mono.Unix/UnixPath.cs
3 //
4 // Authors:
5 //   Jonathan Pryor (jonpryor@vt.edu)
6 //
7 // (C) 2004-2006 Jonathan Pryor
8 //
9 // Permission is hereby granted, free of charge, to any person obtaining
10 // a copy of this software and associated documentation files (the
11 // "Software"), to deal in the Software without restriction, including
12 // without limitation the rights to use, copy, modify, merge, publish,
13 // distribute, sublicense, and/or sell copies of the Software, and to
14 // permit persons to whom the Software is furnished to do so, subject to
15 // the following conditions:
16 // 
17 // The above copyright notice and this permission notice shall be
18 // included in all copies or substantial portions of the Software.
19 // 
20 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
21 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
22 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
23 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
24 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
25 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
26 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
27 //
28
29 using System;
30 using System.Collections;
31 using System.Text;
32 using Mono.Unix;
33
34 namespace Mono.Unix {
35
36         public sealed class UnixPath
37         {
38                 private UnixPath () {}
39
40                 public static readonly char DirectorySeparatorChar = '/';
41                 public static readonly char AltDirectorySeparatorChar = '/';
42                 public static readonly char PathSeparator = ':';
43                 public static readonly char VolumeSeparatorChar = '/';
44
45                 private static readonly char[] _InvalidPathChars = new char[]{};
46
47                 public static char[] GetInvalidPathChars ()
48                 {
49                         return (char[]) _InvalidPathChars.Clone ();
50                 }
51
52                 public static string Combine (string path1, params string[] paths)
53                 {
54                         if (path1 == null)
55                                 throw new ArgumentNullException ("path1");
56                         if (paths == null)
57                                 throw new ArgumentNullException ("paths");
58                         if (path1.IndexOfAny (_InvalidPathChars) != -1)
59                                 throw new ArgumentException ("Illegal characters in path", "path1");
60
61                         int len = path1.Length;
62                         int start = -1;
63                         for (int i = 0; i < paths.Length; ++i) {
64                                 if (paths [i] == null)
65                                         throw new ArgumentNullException ("paths[" + i + "]");
66                                 if (paths [i].IndexOfAny (_InvalidPathChars) != -1)
67                                         throw new ArgumentException ("Illegal characters in path", "paths[" + i + "]");
68                                 if (IsPathRooted (paths [i])) {
69                                         len = 0;
70                                         start = i;
71                                 }
72                                 len += paths [i].Length + 1;
73                         }
74
75                         StringBuilder sb = new StringBuilder (len);
76                         if (start == -1) {
77                                 sb.Append (path1);
78                                 start = 0;
79                         }
80                         for (int i = start; i < paths.Length; ++i)
81                                 Combine (sb, paths [i]);
82                         return sb.ToString ();
83                 }
84
85                 private static void Combine (StringBuilder path, string part)
86                 {
87                         if (path.Length > 0 && part.Length > 0) {
88                                 char end = path [path.Length-1];
89                                 if (end != DirectorySeparatorChar && 
90                                                 end != AltDirectorySeparatorChar && 
91                                                 end != VolumeSeparatorChar)
92                                         path.Append (DirectorySeparatorChar);
93                         }
94                         path.Append (part);
95                 }
96
97                 public static string GetDirectoryName (string path)
98                 {
99                         CheckPath (path);
100
101                         int lastDir = path.LastIndexOf (DirectorySeparatorChar);
102                         if (lastDir > 0)
103                                 return path.Substring (0, lastDir);
104                         return "";
105                 }
106
107                 public static string GetFileName (string path)
108                 {
109                         if (path == null || path.Length == 0)
110                                 return path;
111
112                         int lastDir = path.LastIndexOf (DirectorySeparatorChar);
113                         if (lastDir >= 0)
114                                 return path.Substring (lastDir+1);
115
116                         return path;
117                 }
118
119                 public static string GetFullPath (string path)
120                 {
121                         path = _GetFullPath (path);
122                         return GetCanonicalPath (path);
123                 }
124
125                 private static string _GetFullPath (string path)
126                 {
127                         if (path == null)
128                                 throw new ArgumentNullException ("path");
129                         if (!IsPathRooted (path))
130                                 path = UnixDirectoryInfo.GetCurrentDirectory() + DirectorySeparatorChar + path;
131
132                         return path;
133                 }
134
135                 public static string GetCanonicalPath (string path)
136                 {
137                         string [] dirs;
138                         int lastIndex;
139                         GetPathComponents (path, out dirs, out lastIndex);
140                         string end = string.Join ("/", dirs, 0, lastIndex);
141                         return IsPathRooted (path) ? "/" + end : end;
142                 }
143
144                 private static void GetPathComponents (string path, 
145                         out string[] components, out int lastIndex)
146                 {
147                         string [] dirs = path.Split (DirectorySeparatorChar);
148                         int target = 0;
149                         for (int i = 0; i < dirs.Length; ++i) {
150                                 if (dirs [i] == "." || dirs [i] == string.Empty) continue;
151                                 else if (dirs [i] == "..") {
152                                         if (target != 0) --target;
153                                         else ++target;
154                                 }
155                                 else
156                                         dirs [target++] = dirs [i];
157                         }
158                         components = dirs;
159                         lastIndex = target;
160                 }
161
162                 public static string GetPathRoot (string path)
163                 {
164                         if (path == null)
165                                 return null;
166                         if (!IsPathRooted (path))
167                                 return "";
168                         return "/";
169                 }
170
171                 public static string GetCompleteRealPath (string path)
172                 {
173                         if (path == null)
174                                 throw new ArgumentNullException ("path");
175                         string [] dirs;
176                         int lastIndex;
177                         GetPathComponents (path, out dirs, out lastIndex);
178                         StringBuilder realPath = new StringBuilder ();
179                         if (dirs.Length > 0) {
180                                 string dir = IsPathRooted (path) ? "/" : "";
181                                 dir += dirs [0];
182                                 realPath.Append (GetRealPath (dir));
183                         }
184                         for (int i = 1; i < lastIndex; ++i) {
185                                 realPath.Append ("/").Append (dirs [i]);
186                                 string p = GetRealPath (realPath.ToString());
187                                 realPath.Remove (0, realPath.Length);
188                                 realPath.Append (p);
189                         }
190                         return realPath.ToString ();
191                 }
192
193                 public static string GetRealPath (string path)
194                 {
195                         do {
196                                 string name = ReadSymbolicLink (path);
197                                 if (name == null)
198                                         return path;
199                                 if (IsPathRooted (name))
200                                         path = name;
201                                 else {
202                                         path = GetDirectoryName (path) + DirectorySeparatorChar + name;
203                                         path = GetCanonicalPath (path);
204                                 }
205                         } while (true);
206                 }
207
208                 // Read the specified symbolic link.  If the file isn't a symbolic link,
209                 // return null; otherwise, return the contents of the symbolic link.
210                 //
211                 // readlink(2) is horribly evil, as there is no way to query how big the
212                 // symlink contents are.  Consequently, it's trial and error...
213                 internal static string ReadSymbolicLink (string path)
214                 {
215                         StringBuilder buf = new StringBuilder (256);
216                         do {
217                                 int r = Native.Syscall.readlink (path, buf);
218                                 if (r < 0) {
219                                         Native.Errno e;
220                                         switch (e = Native.Stdlib.GetLastError()) {
221                                         case Native.Errno.EINVAL:
222                                                 // path isn't a symbolic link
223                                                 return null;
224                                         default:
225                                                 UnixMarshal.ThrowExceptionForError (e);
226                                                 break;
227                                         }
228                                 }
229                                 else if (r == buf.Capacity) {
230                                         buf.Capacity *= 2;
231                                 }
232                                 else
233                                         return buf.ToString (0, r);
234                         } while (true);
235                 }
236
237                 // Read the specified symbolic link.  If the file isn't a symbolic link,
238                 // return null; otherwise, return the contents of the symbolic link.
239                 //
240                 // readlink(2) is horribly evil, as there is no way to query how big the
241                 // symlink contents are.  Consequently, it's trial and error...
242                 private static string ReadSymbolicLink (string path, out Native.Errno errno)
243                 {
244                         errno = (Native.Errno) 0;
245                         StringBuilder buf = new StringBuilder (256);
246                         do {
247                                 int r = Native.Syscall.readlink (path, buf);
248                                 if (r < 0) {
249                                         errno = Native.Stdlib.GetLastError ();
250                                         return null;
251                                 }
252                                 else if (r == buf.Capacity) {
253                                         buf.Capacity *= 2;
254                                 }
255                                 else
256                                         return buf.ToString (0, r);
257                         } while (true);
258                 }
259
260                 public static string TryReadLink (string path)
261                 {
262                         Native.Errno errno;
263                         return ReadSymbolicLink (path, out errno);
264                 }
265
266                 public static string ReadLink (string path)
267                 {
268                         Native.Errno errno;
269                         path = ReadSymbolicLink (path, out errno);
270                         if (errno != 0)
271                                 UnixMarshal.ThrowExceptionForError (errno);
272                         return path;
273                 }
274
275                 public static bool IsPathRooted (string path)
276                 {
277                         if (path == null || path.Length == 0)
278                                 return false;
279                         return path [0] == DirectorySeparatorChar;
280                 }
281
282                 internal static void CheckPath (string path)
283                 {
284                         if (path == null)
285                                 throw new ArgumentNullException ();
286                         if (path.Length == 0)
287                                 throw new ArgumentException ("Path cannot contain a zero-length string", "path");
288                         if (path.IndexOfAny (_InvalidPathChars) != -1)
289                                 throw new ArgumentException ("Invalid characters in path.", "path");
290                 }
291         }
292 }
293
294 // vim: noexpandtab