blob: 9c043a82d50db9f969a3921beda56fcf07e4ef16 [file] [log] [blame]
Alexb151fbe2019-04-22 16:53:30 -05001import grp
2import os
3import pwd
4import time
5
6from cfg_checker.common import config
7
8_default_time_format = config.date_format
9
10
11def remove_file(filename):
12 os.remove(filename)
13 # open('filename', 'w').close()
14
15
16def write_str_to_file(filename, _str):
17 with open(filename, 'w') as fo:
18 fo.write(_str)
19
20
21def append_str_to_file(filename, _str):
22 with open(filename, 'a') as fa:
23 fa.write(_str)
24
25
26def write_lines_to_file(filename, source_list):
27 with open(filename, 'w') as fw:
28 fw.write("\n".join(source_list) + "\n")
29
30
31def append_lines_to_file(filename, source_list):
32 _buf = "\n".join(source_list)
33 with open(filename, 'a') as fw:
34 fw.write(_buf + "\n")
35
36
37def append_line_to_file(filename, _str):
38 with open(filename, 'a') as fa:
39 fa.write(_str+'\n')
40
41
42def read_file(filename):
43 _buf = None
44 with open(filename, 'rb') as fr:
45 _buf = fr.read()
46 return _buf
47
48
49def read_file_as_lines(filename):
50 _list = []
51 with open(filename, 'r') as fr:
52 for line in fr:
53 _list.append(line)
54 return _list
55
56
57def get_file_info_fd(fd, time_format=_default_time_format):
58
59 def format_time(unixtime):
60 return time.strftime(
61 time_format,
62 time.gmtime(unixtime)
63 )
64
65 (mode, ino, dev, nlink, uid, gid, size, atime, mtime, ctime) = \
66 os.fstat(fd.fileno())
67
68 _dict = {
69 'fd': fd.fileno(),
70 'mode': oct(mode & 0777),
71 'device': hex(dev),
72 'inode': ino,
73 'hard_links': nlink,
74 'owner_id': uid,
75 'owner_name': pwd.getpwuid(uid).pw_name,
76 'owner_group_name': grp.getgrgid(gid).gr_name,
77 'owner_group_id': gid,
78 'size': size,
79 'access_time': format_time(atime),
80 'modification_time': format_time(mtime),
81 'creation_time': format_time(ctime)
82 }
83
84 return _dict
Alexd9fd85e2019-05-16 16:58:24 -050085
86
87def get_gzipped_file(url):
88 # imports
89 from io import BytesIO
90 from requests import get
91 import gzip
92 # download a file
93 _bytes = BytesIO(get(url).content)
94 with gzip.GzipFile(fileobj=_bytes) as gz:
95 return gz.read()
Alex7f69a6a2019-05-31 16:53:35 -050096
97
98def ensure_folder_exists(_folder):
99 if not os.path.exists(_folder):
100 # it is not exists, create it
101 os.mkdir(_folder)
102 return "... folder '{}' created".format(_folder)
103 else:
104 return "... folder is at '{}'".format(_folder)