Debian Codegraph @

rpython/rlib/rpath.py

raw symbols SCIP
1 """
2 Minimal (and limited) RPython version of some functions contained in os.path.
3 """
4
5 import os, stat
6 from rpython.rlib import rposix
7 from rpython.rlib.signature import signature
8 from rpython.rlib.rstring import assert_str0
9 from rpython.annotator.model import s_Str0
10
11
12 # ____________________________________________________________
13 #
14 # Generic implementations in RPython for both POSIX and NT
15 #
16
17 def risdir(s):
18 """Return true if the pathname refers to an existing directory."""
19 try:
20 st = os.stat(s)
21 except OSError:
22 return False
23 return stat.S_ISDIR(st.st_mode)
24
25
26 # ____________________________________________________________
27 #
28 # POSIX-only implementations
29 #
30
31 def _posix_risabs(s):
32 """Test whether a path is absolute"""
33 return s.startswith('/')
34
35 @signature(s_Str0, returns=s_Str0)
36 def _posix_rnormpath(path):
37 """Normalize path, eliminating double slashes, etc."""
38 slash, dot = '/', '.'
39 assert_str0(dot)
40 if path == '':
41 return dot
42 initial_slashes = path.startswith('/')
43 # POSIX allows one or two initial slashes, but treats three or more
44 # as single slash.
45 if (initial_slashes and
46 path.startswith('//') and not path.startswith('///')):
47 initial_slashes = 2
48 comps = path.split('/')
49 new_comps = []
50 for comp in comps:
51 if comp == '' or comp == '.':
52 continue
53 if (comp != '..' or (not initial_slashes and not new_comps) or
54 (new_comps and new_comps[-1] == '..')):
55 new_comps.append(comp)
56 elif new_comps:
57 new_comps.pop()
58 comps = new_comps
59 path = slash.join(comps)
60 if initial_slashes:
61 path = slash*initial_slashes + path
62 assert_str0(path)
63 return path or dot
64
65 @signature(s_Str0, returns=s_Str0)
66 def _posix_rabspath(path):
67 """Return an absolute, **non-normalized** path.
68 **This version does not let exceptions propagate.**"""
69 try:
70 if not _posix_risabs(path):
71 cwd = os.getcwd()
72 path = _posix_rjoin(cwd, path)
73 assert path is not None
74 return _posix_rnormpath(path)
75 except OSError:
76 return path
77
78 def _posix_rjoin(a, b):
79 """Join two pathname components, inserting '/' as needed.
80 If the second component is an absolute path, the first one
81 will be discarded. An empty last part will result in a path that
82 ends with a separator."""
83 path = a
84 if b.startswith('/'):
85 path = b
86 elif path == '' or path.endswith('/'):
87 path += b
88 else:
89 path += '/' + b
90 return path
91
92
93 # ____________________________________________________________
94 #
95 # NT-only implementations
96 #
97
98 def _nt_risabs(s):
99 """Test whether a path is absolute"""
100 s = _nt_rsplitdrive(s)[1]
101 return s.startswith('/') or s.startswith('\\')
102
103 def _nt_rnormpath(path):
104 """Normalize path, eliminating double slashes, etc."""
105 backslash, dot = '\\', '.'
106 if path.startswith(('\\\\.\\', '\\\\?\\')):
107 # in the case of paths with these prefixes:
108 # \\.\ -> device names
109 # \\?\ -> literal paths
110 # do not do any normalization, but return the path unchanged
111 return path
112 path = path.replace("/", "\\")
113 prefix, path = _nt_rsplitdrive(path)
114 # We need to be careful here. If the prefix is empty, and the path starts
115 # with a backslash, it could either be an absolute path on the current
116 # drive (\dir1\dir2\file) or a UNC filename (\\server\mount\dir1\file). It
117 # is therefore imperative NOT to collapse multiple backslashes blindly in
118 # that case.
119 # The code below preserves multiple backslashes when there is no drive
120 # letter. This means that the invalid filename \\\a\b is preserved
121 # unchanged, where a\\\b is normalised to a\b. It's not clear that there
122 # is any better behaviour for such edge cases.
123 if prefix == '':
124 # No drive letter - preserve initial backslashes
125 while path.startswith("\\"):
126 prefix = prefix + backslash
127 path = path[1:]
128 else:
129 # We have a drive letter - collapse initial backslashes
130 if path.startswith("\\"):
131 prefix = prefix + backslash
132 path = path.lstrip("\\")
133 comps = path.split("\\")
134 i = 0
135 while i < len(comps):
136 if comps[i] in ('.', ''):
137 del comps[i]
138 elif comps[i] == '..':
139 if i > 0 and comps[i-1] != '..':
140 del comps[i-1:i+1]
141 i -= 1
142 elif i == 0 and prefix.endswith("\\"):
143 del comps[i]
144 else:
145 i += 1
146 else:
147 i += 1
148 # If the path is now empty, substitute '.'
149 if not prefix and not comps:
150 comps.append(dot)
151 return prefix + backslash.join(comps)
152
153 @signature(s_Str0, returns=s_Str0)
154 def _nt_rabspath(path):
155 try:
156 if path == '':
157 path = os.getcwd()
158 return rposix.getfullpathname(path)
159 except OSError:
160 return path
161
162 def _nt_rsplitdrive(p):
163 """Split a pathname into drive/UNC sharepoint and relative path
164 specifiers.
165 Returns a 2-tuple (drive_or_unc, path); either part may be empty.
166 """
167 if len(p) > 1:
168 normp = p.replace(altsep, sep)
169 if normp.startswith('\\\\') and not normp.startswith('\\\\\\'):
170 # is a UNC path:
171 # vvvvvvvvvvvvvvvvvvvv drive letter or UNC path
172 # \\machine\mountpoint\directory\etc\...
173 # directory ^^^^^^^^^^^^^^^
174 index = normp.find('\\', 2)
175 if index < 0:
176 return '', p
177 index2 = normp.find('\\', index + 1)
178 # a UNC path can't have two slashes in a row
179 # (after the initial two)
180 if index2 == index + 1:
181 return '', p
182 if index2 < 0:
183 index2 = len(p)
184 return p[:index2], p[index2:]
185 if normp[1] == ':':
186 return p[:2], p[2:]
187 return '', p
188
189 def _nt_rjoin(path, p):
190 """Join two or more pathname components, inserting "\\" as needed."""
191 result_drive, result_path = _nt_rsplitdrive(path)
192 p_drive, p_path = _nt_rsplitdrive(p)
193 p_is_rel = True
194 if p_path and p_path[0] in '\\/':
195 # Second path is absolute
196 if p_drive or not result_drive:
197 result_drive = p_drive
198 result_path = p_path
199 p_is_rel = False
200 elif p_drive and p_drive != result_drive:
201 if p_drive.lower() != result_drive.lower():
202 # Different drives => ignore the first path entirely
203 result_drive = p_drive
204 result_path = p_path
205 p_is_rel = False
206 else:
207 # Same drive in different case
208 result_drive = p_drive
209 if p_is_rel:
210 # Second path is relative to the first
211 if result_path and result_path[-1] not in '\\/':
212 result_path = result_path + '\\'
213 result_path = result_path + p_path
214 ## add separator between UNC and non-absolute path
215 if (result_path and result_path[0] not in '\\/' and
216 result_drive and result_drive[-1] != ':'):
217 return result_drive + '\\' + result_path
218 return result_drive + result_path
219
220
221 # ____________________________________________________________
222
223
224 if os.name == 'posix':
225 sep = altsep = '/'
226 risabs = _posix_risabs
227 rnormpath = _posix_rnormpath
228 rabspath = _posix_rabspath
229 rjoin = _posix_rjoin
230 elif os.name == 'nt':
231 sep, altsep = '\\', '/'
232 risabs = _nt_risabs
233 rnormpath = _nt_rnormpath
234 rabspath = _nt_rabspath
235 rsplitdrive = _nt_rsplitdrive
236 rjoin = _nt_rjoin
237 else:
238 raise ImportError('Unsupported os: %s' % os.name)