-
Notifications
You must be signed in to change notification settings - Fork 0
/
product_selector.py
executable file
·48 lines (44 loc) · 2.13 KB
/
product_selector.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
import fnmatch
import glob
import os
import zipfile
class ProductSelector:
def __init__(self, glob_selector):
self.selector = glob_selector
def isproduct(self, filepath):
if not os.path.exists(filepath):
raise Exception("File not found")
if zipfile.is_zipfile(filepath):
with zipfile.ZipFile(filepath, 'r') as z:
namelist = [n for n in z.namelist() if fnmatch.fnmatch(n, self.selector)]
if len(namelist) > 1:
raise Exception("Invalid product selector or product archive: more than one file is being selected")
return len(namelist) == 1
elif os.path.isfile(filepath):
return True
elif os.path.isdir(filepath):
files = glob.glob(os.path.join(filepath, self.selector))
if len(files) > 1:
raise Exception("Invalid product selector or product archive: more than one file is being selected")
return len(files) == 1
def openproduct(self, filepath):
if not os.path.exists(filepath):
raise Exception("File not found")
if zipfile.is_zipfile(filepath):
with zipfile.ZipFile(filepath, 'r') as z:
namelist = [n for n in z.namelist() if fnmatch.fnmatch(n, self.selector)]
if not namelist:
raise Exception("Invalid product selector or product archive: no file is being selected")
if len(namelist) > 1:
raise Exception("Invalid product selector or product archive: more than one file is being selected")
z.extractall()
return namelist[0]
elif os.path.isfile(filepath):
return filepath
elif os.path.isdir(filepath):
files = glob.glob(os.path.join(filepath, self.selector))
if not files:
raise Exception("Invalid product selector or product archive: no file is being selected")
if len(files) > 1:
raise Exception("Invalid product selector or product archive: more than one file is being selected")
return files[0]