This repository has been archived by the owner on Dec 14, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathutil.py
62 lines (47 loc) · 2.17 KB
/
util.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
import os
import magic
import logging
from pathlib import Path
from ..parser import File
log = logging.getLogger('credshed.filestore.util')
def delete_dir(dirname):
'''
Remove a directory if it's empty or only contains empty files
'''
try:
dirname = Path(dirname).resolve()
for file in list_files(dirname):
if file.size == 0:
log.debug(f'Deleting empty file {file}')
file.unlink()
dirname.rmdir()
except (OSError, PermissionError) as e:
log.debug(f'Error deleting directory {dirname}')
def list_files(path, include_symlinks=False):
path = Path(path)
if path.is_file():
yield File(path)
elif path.is_dir():
for dir_name, dir_list, file_list in os.walk(path, followlinks=False):
#log.debug(f'Found dir: {dir_name}')
for f in file_list:
file = File(Path(dir_name) / f)
if file.is_file() or (include_symlinks and file.is_symlink()):
yield file
else:
log.debug(f'Not a file: {file}')
else:
log.warning(f'Unable to list files in {path}')
supported_compressions = [
# magic string # command for decompression
('microsoft excel', ['ssconvert', '-S', '{filename}', '{extract_dir}/%s.csv']),
('rar archive', ['unrar', 'x', '-o+', '-p-', '{filename}', '{extract_dir}/']),
('tar archive', ['tar', '--overwrite', '-xvf', '{filename}', '-C', '{extract_dir}/']),
('gzip compressed', ['tar', '--overwrite', '-xvzf', '{filename}', '-C', '{extract_dir}/']),
('gzip compressed', ['gunzip', '--force', '--keep', '{filename}']),
('bzip2 compressed', ['tar', '--overwrite', '-xvjf', '{filename}', '-C', '{extract_dir}/']),
('xz compressed', ['tar', '--overwrite', '-xvJf', '{filename}', '-C', '{extract_dir}/']),
('lzma compressed', ['tar', '--overwrite', '--lzma', '-xvf', '{filename}', '-C', '{extract_dir}/']),
('7-zip archive', ['7z', 'x', '-p""', '-aoa', '{filename}', '-o{extract_dir}/']),
('zip archive', ['7z', 'x', '-p""', '-aoa', '{filename}', '-o{extract_dir}/']),
]