path_util.py revision 5d1f7b1de12d16ceb2c938c56701a3e8bfa558f7
1# Copyright 2013 The Chromium Authors. All rights reserved.
2# Use of this source code is governed by a BSD-style license that can be
3# found in the LICENSE file.
4
5import posixpath
6
7
8# TODO(kalman): Write a Path class and use that everywhere rather than a
9# utility class.
10
11
12def IsDirectory(path):
13  '''Returns whether |path| should be considered a directory.
14  '''
15  # This assertion is sprinkled throughout the code base.
16  AssertIsValid(path)
17  return path in ('', '.', '..') or path.endswith('/') or path.endswith('/..')
18
19
20def IsValid(path):
21  '''Returns whether |path| is a valid path for the purposes of the docserver.
22  Paths may not start with /, must be posix paths, and for sanity shouldn't
23  repeat the path separator //.
24  '''
25  return not path.startswith('/') and not '\\' in path and not '//' in path
26
27
28def AssertIsValid(path):
29  assert IsValid(path), 'Path "%s" is invalid' % path
30
31
32def Join(*paths):
33  assert all(IsValid(path) for path in paths), paths
34  return posixpath.join(*paths)
35
36
37def SplitParent(path):
38  '''Returns the parent directory and base name of |path| in a tuple.
39  Any trailing slash of |path| is preserved, such that the parent of
40  '/hello/world/' is '/hello' and the base is 'world/'.
41  '''
42  parent, base = posixpath.split(path.rstrip('/'))
43  if path.endswith('/'):
44    base += '/'
45  return parent, base
46
47
48def ToDirectory(path):
49  '''Returns a string representing |path| as a directory, that is,
50  IsDirectory(result) is True (and does not fail assertions). If |path| is
51  already a directory then this is a no-op.
52  '''
53  return path if IsDirectory(path) else (path + '/')
54
55
56def AssertIsDirectory(path):
57  assert IsDirectory(path), '"%s" is not a directory' % path
58
59
60def AssertIsFile(path):
61  assert not IsDirectory(path), '"%s" is not a file' % path
62