Mercurial > public > mercurial-scm > hg-stable
comparison mercurial/pathutil.py @ 25281:660b178f49c7
pathutil: add dirname and join functions
This adds dirname and join functions to pathutil which are explicitly for
handling '/' delimited paths. The implementations are basically copy paste from
python's posix os.path.dirname and os.path.join functions.
author | Durham Goode <durham@fb.com> |
---|---|
date | Fri, 22 May 2015 12:47:18 -0700 |
parents | 10bbdcd89164 |
children | 46f2df2f0680 |
comparison
equal
deleted
inserted
replaced
25280:8c8af4d8aca3 | 25281:660b178f49c7 |
---|---|
185 d, p = os.path.splitdrive(path) | 185 d, p = os.path.splitdrive(path) |
186 if len(p) != len(os.sep): | 186 if len(p) != len(os.sep): |
187 return path + os.sep | 187 return path + os.sep |
188 else: | 188 else: |
189 return path | 189 return path |
190 | |
191 def join(path, *paths): | |
192 '''Join two or more pathname components, inserting '/' as needed. | |
193 | |
194 Based on the posix os.path.join() implementation. | |
195 | |
196 >>> join('foo', 'bar') | |
197 'foo/bar' | |
198 >>> join('/foo', 'bar') | |
199 '/foo/bar' | |
200 >>> join('foo', '/bar') | |
201 '/bar' | |
202 >>> join('foo', 'bar/') | |
203 'foo/bar/' | |
204 >>> join('foo', 'bar', 'gah') | |
205 'foo/bar/gah' | |
206 >>> join('foo') | |
207 'foo' | |
208 >>> join('', 'foo') | |
209 'foo' | |
210 >>> join('foo/', 'bar') | |
211 'foo/bar' | |
212 >>> join('', '', '') | |
213 '' | |
214 >>> join ('foo', '', '', 'bar') | |
215 'foo/bar' | |
216 ''' | |
217 sep = '/' | |
218 if not paths: | |
219 path[:0] + sep #23780: Ensure compatible data type even if p is null. | |
220 for piece in paths: | |
221 if piece.startswith(sep): | |
222 path = piece | |
223 elif not path or path.endswith(sep): | |
224 path += piece | |
225 else: | |
226 path += sep + piece | |
227 return path | |
228 | |
229 def dirname(path): | |
230 '''returns the directory portion of the given path | |
231 | |
232 Based on the posix os.path.split() implementation. | |
233 | |
234 >>> dirname('foo') | |
235 '' | |
236 >>> dirname('foo/') | |
237 'foo' | |
238 >>> dirname('foo/bar') | |
239 'foo' | |
240 >>> dirname('/foo') | |
241 '/' | |
242 >>> dirname('/foo/bar') | |
243 '/foo' | |
244 >>> dirname('/foo//bar/poo') | |
245 '/foo//bar' | |
246 >>> dirname('/foo//bar') | |
247 '/foo' | |
248 ''' | |
249 sep = '/' | |
250 i = path.rfind(sep) + 1 | |
251 dirname = path[:i] | |
252 if dirname and dirname != sep * len(dirname): | |
253 dirname = dirname.rstrip(sep) | |
254 return dirname |