Debian Codegraph @

ansible_collections/azure/azcollection/plugins/plugin_utils/file_utils.py

raw symbols SCIP
1 # --------------------------------------------------------------------------------------------
2 # Copyright (c) Microsoft Corporation. All rights reserved.
3 # Licensed under the MIT License. See License.txt in the project root for license information.
4 # --------------------------------------------------------------------------------------------
5
6 import errno
7 import os
8
9 from ansible.utils.display import Display
10 from ansible_collections.azure.azcollection.plugins.plugin_utils import constants as consts
11 from ansible.errors import AnsibleError
12
13
14 display = Display()
15
16
17 def make_dirs_for_file(file_path):
18 if not os.path.exists(file_path):
19 mkdir_p(os.path.dirname(file_path))
20
21
22 def mkdir_p(path):
23 try:
24 os.makedirs(path)
25 except OSError as exc: # Python <= 2.5
26 if exc.errno == errno.EEXIST and os.path.isdir(path):
27 pass
28 else:
29 raise
30
31
32 def delete_file(file_path, message, warning=False):
33 # pylint: disable=broad-except
34 if os.path.isfile(file_path):
35 try:
36 os.remove(file_path)
37 except Exception as e:
38 if warning:
39 display(message)
40 else:
41 raise AnsibleError(message + "Error: " + str(e)) from e
42
43
44 def delete_folder(dir_path, message, warning=False):
45 # pylint: disable=broad-except
46 if os.path.isdir(dir_path):
47 try:
48 os.rmdir(dir_path)
49 except Exception as e:
50 if warning:
51 display(message)
52 else:
53 raise AnsibleError(message + "Error: " + str(e)) from e
54
55
56 def create_directory(file_path, error_message):
57 try:
58 os.makedirs(file_path)
59 except Exception as e:
60 raise AnsibleError(error_message + "Error: " + str(e)) from e
61
62
63 def write_to_file(file_path, mode, content, error_message, encoding=None):
64 # pylint: disable=unspecified-encoding
65 try:
66 if encoding:
67 with open(file_path, mode, encoding=encoding) as f:
68 f.write(content)
69 else:
70 with open(file_path, mode) as f:
71 f.write(content)
72 except Exception as e:
73 raise AnsibleError(error_message + "Error: " + str(e)) from e
74
75
76 def get_line_that_contains(substring, lines):
77 for line in lines:
78 if substring in line:
79 return line
80 return None
81
82
83 def remove_invalid_characters_foldername(folder_name):
84 new_foldername = ""
85 for c in folder_name:
86 if c not in consts.WINDOWS_INVALID_FOLDERNAME_CHARS:
87 new_foldername += c
88 return new_foldername