Debian Codegraph @

behave4cmd0/pathutil.py

raw
1 # -*- coding -*-
2 """
3 Provides some command utility functions.
4
5 TODO:
6 matcher that ignores empty lines and whitespace and has contains comparison
7 """
8
9 from __future__ import absolute_import, print_function
10 import os.path
11 import sys
12 import codecs
13
14
15 # -----------------------------------------------------------------------------
16 # CONSTANTS:
17 # -----------------------------------------------------------------------------
18 # HERE, WORKDIR: see "__setup.py"
19
20
21 # -----------------------------------------------------------------------------
22 # UTILITY FUNCTIONS:
23 # -----------------------------------------------------------------------------
24 def realpath_with_context(path, context):
25 """
26 Convert a path into its realpath:
27
28 * For relative path: use :attr:`context.workdir` as root directory
29 * For absolute path: Pass-through without any changes.
30
31 :param path: Filepath to convert (as string).
32 :param context: Behave context object (with :attr:`context.workdir`)
33 :return: Converted path.
34 """
35 if not os.path.isabs(path):
36 # XXX ensure_workdir_exists(context)
37 assert context.workdir
38 path = os.path.join(context.workdir, os.path.normpath(path))
39 return path
40
41 def posixpath_normpath(pathname):
42 """
43 Convert path into POSIX path:
44
45 * Normalize path
46 * Replace backslash with slash
47
48 :param pathname: Pathname (as string)
49 :return: Normalized POSIX path.
50 """
51 backslash = '\\'
52 pathname2 = os.path.normpath(pathname) or "."
53 if backslash in pathname2:
54 pathname2 = pathname2.replace(backslash, '/')
55 return pathname2
56
57
58 def ensure_makedirs(directory, max_iterations=3):
59 # -- SPORADIC-ERRORS: WindowsError: [Error 5] Access denied: '...'
60 iteration = 0
61 exception_text = None
62 for iteration in range(max_iterations):
63 try:
64 os.makedirs(directory)
65 except OSError as e:
66 if iteration >= max_iterations: # XXX-BAD: Never occurs
67 raise
68 else:
69 exception_text = "%s:%s" % (e.__class__.__name__, e)
70
71 if os.path.isdir(directory):
72 return
73
74 assert os.path.isdir(directory), \
75 "FAILED: ensure_makedirs(%r) (after %s iterations):\n%s" % \
76 (directory, max_iterations, exception_text)
77
78
79 def read_file_contents(filename, context=None, encoding=None):
80 filename_ = realpath_with_context(filename, context)
81 assert os.path.exists(filename_)
82 with open(filename_, "r") as file_:
83 file_contents = file_.read()
84 return file_contents
85
86
87 # def create_new_workdir(context):
88 # ensure_attribute_exists(context, "workdir", default=WORKDIR)
89 # if os.path.exists(context.workdir):
90 # shutil.rmtree(context.workdir, ignore_errors=True)
91 # ensure_workdir_exists(context)
92
93
94 def create_textfile_with_contents(filename, contents, encoding='utf-8'):
95 """
96 Creates a textual file with the provided contents in the workdir.
97 Overwrites an existing file.
98 """
99 ensure_directory_exists(os.path.dirname(filename))
100 if os.path.exists(filename):
101 os.remove(filename)
102 outstream = codecs.open(filename, "w", encoding)
103 outstream.write(contents)
104 if contents and not contents.endswith("\n"):
105 outstream.write("\n")
106 outstream.flush()
107 outstream.close()
108 assert os.path.exists(filename), "ENSURE file exists: %s" % filename
109
110
111 def ensure_file_exists(filename, context=None):
112 real_filename = filename
113 if context:
114 real_filename = realpath_with_context(filename, context)
115 if not os.path.exists(real_filename):
116 create_textfile_with_contents(real_filename, "")
117 assert os.path.exists(real_filename), "ENSURE file exists: %s" % filename
118
119
120 def ensure_directory_exists(dirname, context=None):
121 """Ensures that a directory exits.
122 If it does not exist, it is automatically created.
123 """
124 real_dirname = dirname
125 if context:
126 real_dirname = realpath_with_context(dirname, context)
127 if not os.path.exists(real_dirname):
128 mas_iterations = 2
129 if sys.platform.startswith("win"):
130 mas_iterations = 10
131 ensure_makedirs(real_dirname, mas_iterations)
132
133 assert os.path.exists(real_dirname), "ENSURE dir exists: %s" % dirname
134 assert os.path.isdir(real_dirname), "ENSURE isa dir: %s" % dirname
135
136
137 # def ensure_workdir_exists(context):
138 # """
139 # Ensures that the work directory exists.
140 # In addition, the location of the workdir is stored as attribute in
141 # the context object.
142 # """
143 # ensure_attribute_exists(context, "workdir", default=WORKDIR)
144 # # if not context.workdir:
145 # # context.workdir = os.path.abspath(WORKDIR)
146 # ensure_directory_exists(context.workdir)