Debian Codegraph @

behave4cmd0/command_util.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 from behave4cmd0 import pathutil
11 from behave4cmd0.__setup import TOP, TOPA
12 import os.path
13 import sys
14 import shutil
15 import time
16 import tempfile
17 from fnmatch import fnmatch
18
19 # -----------------------------------------------------------------------------
20 # CONSTANTS:
21 # -----------------------------------------------------------------------------
22 # HERE = os.path.dirname(__file__)
23 # TOP = os.path.join(HERE, "..")
24 # TOPA = os.path.abspath(TOP)
25 WORKDIR = os.path.join(TOP, "__WORKDIR__")
26
27
28 # -----------------------------------------------------------------------------
29 # UTILITY FUNCTIONS:
30 # -----------------------------------------------------------------------------
31 def workdir_save_coverage_files(workdir, destdir=None):
32 assert os.path.isdir(workdir)
33 if not destdir:
34 destdir = TOPA
35 if os.path.abspath(workdir) == os.path.abspath(destdir):
36 return # -- SKIP: Source directory is destination directory (SAME).
37
38 for fname in os.listdir(workdir):
39 if fnmatch(fname, ".coverage.*"):
40 # -- MOVE COVERAGE FILES:
41 sourcename = os.path.join(workdir, fname)
42 shutil.move(sourcename, destdir)
43
44 # def ensure_directory_exists(dirname):
45 # """
46 # Ensures that a directory exits.
47 # If it does not exist, it is automatically created.
48 # """
49 # if not os.path.exists(dirname):
50 # os.makedirs(dirname)
51 # assert os.path.exists(dirname)
52 # assert os.path.isdir(dirname)
53
54 def ensure_context_attribute_exists(context, name, default_value=None):
55 """
56 Ensure a behave resource exists as attribute in the behave context.
57 If this is not the case, the attribute is created by using the default_value.
58 """
59 if not hasattr(context, name):
60 setattr(context, name, default_value)
61
62 def ensure_workdir_exists(context):
63 """
64 Ensures that the work directory exists.
65 In addition, the location of the workdir is stored as attribute in
66 the context object.
67 """
68 ensure_context_attribute_exists(context, "workdir", None)
69 if not context.workdir:
70 context.workdir = os.path.abspath(WORKDIR)
71 pathutil.ensure_directory_exists(context.workdir)
72
73 def ensure_workdir_not_exists(context):
74 """Ensures that the work directory does not exist."""
75 ensure_context_attribute_exists(context, "workdir", None)
76 if context.workdir:
77 orig_dirname = real_dirname = context.workdir
78 context.workdir = None
79 if os.path.exists(real_dirname):
80 renamed_dirname = tempfile.mktemp(prefix=os.path.basename(real_dirname),
81 suffix="_DEAD",
82 dir=os.path.dirname(real_dirname) or ".")
83 os.rename(real_dirname, renamed_dirname)
84 real_dirname = renamed_dirname
85 max_iterations = 2
86 if sys.platform.startswith("win"):
87 max_iterations = 15
88
89 for iteration in range(max_iterations):
90 if not os.path.exists(real_dirname):
91 if iteration > 1:
92 print("REMOVE-WORKDIR after %s iterations" % (iteration+1))
93 break
94 shutil.rmtree(real_dirname, ignore_errors=True)
95 time.sleep(0.5)
96 assert not os.path.isdir(real_dirname), "ENSURE not-isa dir: %s" % real_dirname
97 assert not os.path.exists(real_dirname), "ENSURE dir not-exists: %s" % real_dirname
98 assert not os.path.isdir(orig_dirname), "ENSURE not-isa dir: %s" % orig_dirname
99
100
101 # def create_textfile_with_contents(filename, contents):
102 # """
103 # Creates a textual file with the provided contents in the workdir.
104 # Overwrites an existing file.
105 # """
106 # ensure_directory_exists(os.path.dirname(filename))
107 # if os.path.exists(filename):
108 # os.remove(filename)
109 # outstream = open(filename, "w")
110 # outstream.write(contents)
111 # if not contents.endswith("\n"):
112 # outstream.write("\n")
113 # outstream.flush()
114 # outstream.close()
115 # assert os.path.exists(filename)
116
117 # def text_remove_empty_lines(text):
118 # """
119 # Whitespace normalization:
120 # - Strip empty lines
121 # - Strip trailing whitespace
122 # """
123 # lines = [ line.rstrip() for line in text.splitlines() if line.strip() ]
124 # return "\n".join(lines)
125 #
126 # def text_normalize(text):
127 # """
128 # Whitespace normalization:
129 # - Strip empty lines
130 # - Strip leading whitespace in a line
131 # - Strip trailing whitespace in a line
132 # - Normalize line endings
133 # """
134 # lines = [ line.strip() for line in text.splitlines() if line.strip() ]
135 # return "\n".join(lines)
136
137 # def posixpath_normpath(pathname):
138 # """
139 # Convert path into POSIX path:
140 # - Normalize path
141 # - Replace backslash with slash
142 # """
143 # backslash = '\\'
144 # pathname = os.path.normpath(pathname)
145 # if backslash in pathname:
146 # pathname = pathname.replace(backslash, '/')
147 # return pathname