blob: 8b1652a4f3bcebb8142d978293dea1c51bd3e862 [file] [log] [blame]
Alex0989ecf2022-03-29 13:43:21 -05001# Author: Alex Savatieiev (osavatieiev@mirantis.com; a.savex@gmail.com)
2# Copyright 2019-2022 Mirantis, Inc.
Alex9a4ad212020-10-01 18:04:25 -05003import atexit
Alexb151fbe2019-04-22 16:53:30 -05004import grp
5import os
6import pwd
7import time
Alex9a4ad212020-10-01 18:04:25 -05008import tempfile
Alexb151fbe2019-04-22 16:53:30 -05009
Alex9a4ad212020-10-01 18:04:25 -050010_default_time_format = "%Y-%m-%d %H:%M:%S.%f%z"
11_temp_files = {}
Alexb151fbe2019-04-22 16:53:30 -050012
13
14def remove_file(filename):
15 os.remove(filename)
16 # open('filename', 'w').close()
17
18
19def write_str_to_file(filename, _str):
20 with open(filename, 'w') as fo:
21 fo.write(_str)
22
23
24def append_str_to_file(filename, _str):
25 with open(filename, 'a') as fa:
26 fa.write(_str)
27
28
29def write_lines_to_file(filename, source_list):
30 with open(filename, 'w') as fw:
31 fw.write("\n".join(source_list) + "\n")
32
33
34def append_lines_to_file(filename, source_list):
35 _buf = "\n".join(source_list)
36 with open(filename, 'a') as fw:
37 fw.write(_buf + "\n")
38
39
40def append_line_to_file(filename, _str):
41 with open(filename, 'a') as fa:
42 fa.write(_str+'\n')
43
44
45def read_file(filename):
46 _buf = None
47 with open(filename, 'rb') as fr:
48 _buf = fr.read()
49 return _buf
50
51
52def read_file_as_lines(filename):
53 _list = []
Alex1839bbf2019-08-22 17:17:21 -050054 with open(filename, 'rt') as fr:
Alexb151fbe2019-04-22 16:53:30 -050055 for line in fr:
Alex1839bbf2019-08-22 17:17:21 -050056 _list.append(line.rstrip())
Alexb151fbe2019-04-22 16:53:30 -050057 return _list
58
59
60def get_file_info_fd(fd, time_format=_default_time_format):
61
62 def format_time(unixtime):
63 return time.strftime(
64 time_format,
65 time.gmtime(unixtime)
66 )
67
68 (mode, ino, dev, nlink, uid, gid, size, atime, mtime, ctime) = \
69 os.fstat(fd.fileno())
70
71 _dict = {
72 'fd': fd.fileno(),
Alex3bc95f62020-03-05 17:00:04 -060073 'mode': oct(mode & 0o777),
Alexb151fbe2019-04-22 16:53:30 -050074 'device': hex(dev),
75 'inode': ino,
76 'hard_links': nlink,
77 'owner_id': uid,
78 'owner_name': pwd.getpwuid(uid).pw_name,
79 'owner_group_name': grp.getgrgid(gid).gr_name,
80 'owner_group_id': gid,
81 'size': size,
82 'access_time': format_time(atime),
83 'modification_time': format_time(mtime),
84 'creation_time': format_time(ctime)
85 }
86
87 return _dict
Alexd9fd85e2019-05-16 16:58:24 -050088
89
90def get_gzipped_file(url):
91 # imports
92 from io import BytesIO
93 from requests import get
94 import gzip
95 # download a file
96 _bytes = BytesIO(get(url).content)
97 with gzip.GzipFile(fileobj=_bytes) as gz:
98 return gz.read()
Alex7f69a6a2019-05-31 16:53:35 -050099
100
101def ensure_folder_exists(_folder):
102 if not os.path.exists(_folder):
103 # it is not exists, create it
104 os.mkdir(_folder)
105 return "... folder '{}' created".format(_folder)
106 else:
Alexb2129542021-11-23 15:49:42 -0600107 return "... folder exists at '{}'".format(_folder)
Alex3bc95f62020-03-05 17:00:04 -0600108
109
110def ensure_folder_removed(_folder):
111 if os.path.exists(_folder):
112 os.rmdir(_folder)
113 return "... folder '{}' removed".format(_folder)
114 else:
115 return "... folder '{}' not exists".format(_folder)
Alex9a4ad212020-10-01 18:04:25 -0500116
117
118def _cleanup_temp_files():
119 global _temp_files
120 for temp_file in _temp_files.values():
121 try:
122 os.remove(temp_file)
123 except OSError:
124 pass
125 _temp_files = {}
126
127
128def create_temp_file_with_content(content, mode=None):
129 if len(_temp_files) == 0:
130 atexit.register(_cleanup_temp_files)
131 # Because we may change context several times, try to remember files we
132 # created and reuse them at a small memory cost.
133 content_key = hash(content)
134 if content_key in _temp_files:
135 return _temp_files[content_key]
136
137 # new file, create it
138 _, name = tempfile.mkstemp()
139 _temp_files[content_key] = name
140 with open(name, 'wb') as fd:
141 fd.write(content.encode() if isinstance(content, str) else content)
142
143 # set mode for the file
144 if mode:
145 os.chmod(name, mode)
146
147 return name