# Coverage for api/file.py : 16%

## 80 statements

Hot-keys on this page

r m x p toggle line displays

j k next/prev highlighted chunk

0 (zero) top of page

1 (one) first highlighted chunk

1 import os

2 import shutil

3 import uuid

4

5 import click

6

7# from werkzeug.utils import secure_filename

8

9

10 def tryrmcache(dir_name, verbose=False):

11 """

12 removes all __pycache__ starting from directory dir_name

13 all the way to leaf directory

14

15 Args:

16 dir_name(string) : path from where to start removing pycache

17 """

18 # directory_list = list()

19 is_removed = False

20 for root, dirs, _ in os.walk(dir_name, topdown=False):

21 for name in dirs:

22 # directory_list.append(os.path.join(root, name))

23 if name == "__pycache__":

24 shutil.rmtree(os.path.join(root, name))

25 is_removed = True

26

27 if verbose:

28 if is_removed:

29 click.echo("[x] __pycache__ successfully deleted")

30 else:

31 click.echo("[ ] __pycache__ doesn't exist", err=True)

32

33 return is_removed

34

35

36 def tryrmfile(path, verbose=False):

37 """

38 tries to remove file path and output message to stdin or stderr.

39 Path must point to a file

40

41 Args:

42 path (string): path of the file to remove

43

44 Returns:

45 bool: returns true upon successful removal false otherwise

46 """

47 try:

48 os.remove(path)

49 if verbose:

50 click.echo(f"[x] file '{path}' successfully deleted")

51 return True

52 except OSError as e:

53 if verbose:

54 click.echo(

55 f"[ ] unable to delete {e.filename}: {e.strerror}",

56 err=True,

57 )

58 return False

59

60

61 def tryrmtree(path, verbose=False):

62 """

63 Tries to removes an entire directory tree. Path must point to

64 a directory. Outputs message to stdin or stderr

65

66 Args:

67 path (string): directory path to be removed

68

69 Returns:

70 bool: returns true upon successful return false otherwise

71 """

72 try:

73 shutil.rmtree(path)

74 if verbose:

75 click.echo(f"[x] folder '{path}' successfully deleted")

76 return True

77 except OSError as e:

78 if verbose:

79 click.echo(

80 f"[ ] unable to delete {e.filename}: {e.strerror}",

81 err=True,

82 )

83 return False

84

85

86 def trycopytree(source, dest, verbose=False):

87 """

88 Recursive copy of folder

89

90 Parameters

91 ----------

92 source: str

93 source folder path

94 dest: str

95 destination folder path

96

97 Returns

98 -------

99 None

100 """

101 try:

102 shutil.copytree(source, dest)

103 if verbose:

104 print(f"[x] done copying {source} to {dest}")

105 except Exception as e:

106 print(f"[ ] unable to copy directory tree. {e}")

107

108

109 def trycopy(source, dest, verbose=False):

110 """

111 Non-ecursive copy of folder

112

113 Parameters

114 ----------

115 source: str

116 source folder path

117 dest: str

118 destination folder path

119

120 Returns

121 -------

122 None

123 """

124 try:

125 shutil.copy(source, dest)

126 if verbose:

127 print(f"[x] done copying {source} to {dest}")

128 except Exception as e:

129 print(f"[ ] unable to copy file. {e}")

130

131

132 def trymkdir(path, verbose=False):

133 """

134 Creates dir at destination

135

136 Parameters

137 ----------

138 path: str

139 path with folder already in

140

141 Returns

142 -------

143 None

144 """

145 try:

146 os.mkdir(path)

147 if verbose:

148 print(f"[x] Successfully created dir {path}")

149 except Exception as e:

150 print(f"[ ] unable to make directory. {e}")

151

152

153 def trymkfile(path, content, verbose=False):

154 """

155 Creates file

156

157 Parameters

158 ----------

159 path: str

160 path to create file with filename included

161 content: str

162 file content

163

164 Returns

165 -------

166 None

167 """

168 try:

169 with open(path, "w+") as f:

170 f.write(content)

171 if verbose:

172 click.echo(f"[x] file {path} created with content: ")

173 click.echo(content)

174 except Exception as e:

175 click.echo(f"[ ] {e}")

176

177

178 def absdiroffile(filepath):

179 """

180 Gives absolute directory of file, normally expects __file__ as

181 param

182

183 Parameters

184 ----------

185 filepath: str

186 path of file

187

188 Returns

189 -------

190 str

191 Absolute dir path of file

192 """

193 return os.path.dirname(os.path.abspath(filepath))

194

195

196 def get_folders(path):

197 dirs = [d for d in os.listdir(path) if os.path.isdir(os.path.join(path, d))]

198 return dirs

199

200

201 def unique_filename(fname):

202 prepended = str(uuid.uuid4()).replace("-", "_")[:10]

203 return f"{prepended}_{fname}"

204

205

206 def path_exists(path):

207 return os.path.exists(path)

208

209

210 def last_part_of_path(path):

211 return os.path.basename(os.path.normpath(path))

212

213

214 def delete_file(path):

215 os.remove(path)

216

217

218# def unique_sec_filename(filename):

219# return unique_filename(secure_filename(filename))