from .logger import logger
import re
from . import interaction as IH
[docs]def ensurePathExists(path, ask=False): #http://stackoverflow.com/a/5032238
import os, errno
if path == '': return
if not os.path.isdir(path):
if ask and not IH.promptYN('{0} does not exist, create?'.format(path)):
raise OSError("Didn't create Directory")
try:
os.makedirs(path)
logger.info('{0} has been created'.format(path))
except OSError as exception:
if exception.errno != errno.EEXIST:
raise
[docs]def cleanAndCheckPath(path):
path = cleanPath(path)
checkPath(path)
return path
substitutions = [('\*', '_star_'),
('<', '_lt_'),
('>', '_gt_'),
('=', '_eq_'),
('\+', '_plus_'),
('\(', '_lp_'),
('\)', '_rp_'),
('\[', '_lsb_'),
('\]', '_rsb_'),
('\|\|', '_or_'),
('@', '_at_'),
(':', '_sc_'),
('\.', '_dot_'),
('&&', '_and_'),
]
[docs]def cleanPath(path):
for pattern, sub in substitutions:
path = re.sub(pattern, sub, path)
return path
[docs]def checkPath(path):
import string
allowedCharacters = string.ascii_letters + string.digits + '_' + '-' + '/'
if set(allowedCharacters).issuperset(path):
logger.debug("path {} is accepted".format(path))
else:
logger.warning('{} not in {}'.format(path, allowedCharacters))
logger.warning('---> possible problem?', set(path) - set(allowedCharacters))
raise ValueError
[docs]def filesInDir(directory, patterns=[""], matchAll=True):
from . import container as C
import os, re
pathDict = {}
fileList = [ os.path.join(directory, ifile) for ifile in os.listdir(directory)]
nMatches = 0
for pattern in patterns:
pathDict[pattern] = []
for f in fileList:
search = re.search(pattern, f)
if search is not None:
nMatches += 1
pathDict[pattern].append(f)
if not C.checkUniqueValues(pathDict):
raise KeyError
if nMatches != len(fileList) and matchAll:
invDict = C.invertDict(pathDict)
print(invDict)
for f in set(fileList) - set(C.getValues(pathDict)):
logger.warning("some samples not matched: {}".format(f))
raise KeyError
return pathDict