athena-test/server/model/file_provider.py

55 lines
1.7 KiB
Python

import os
import codecs
import config.env as env
def has_allowed_extension(name, allowed_file_endings=None):
if not allowed_file_endings: return True
for file_ending in allowed_file_endings:
if name.endswith(file_ending):
return True
return False
def collect_nested_files(directory_path, forbidden_dir_names=None, allowed_file_endings=None, collected_paths=None):
if not forbidden_dir_names: forbidden_dir_names = ['env', '.git', '__pycache__', 'server']
if not allowed_file_endings: allowed_file_endings = ['.md']
if not collected_paths: collected_paths = []
print(directory_path)
if any(name in directory_path.split('\\') + directory_path.split('/') for name in forbidden_dir_names): return
collected_paths = ((directory_path, []))
subpaths = collected_paths[1]
nested_list = sorted(os.listdir(directory_path))
for name in nested_list:
nested_path = os.path.join(directory_path, name)
if os.path.isdir(nested_path):
nested_dir = collect_nested_files(nested_path, collected_paths=subpaths)
if nested_dir:
subpaths.append(nested_dir)
else:
if not has_allowed_extension(name, allowed_file_endings=allowed_file_endings): continue
subpaths.append(nested_path)
return collected_paths
def read_file(file_path):
with codecs.open(
os.path.join(env.working_dir, file_path),
encoding=env.encoding,
mode='r'
) as file:
return file.read()
def write_file(file_path, content, create_dirs=True):
if create_dirs:
os.makedirs(os.path.dirname(file_path), exist_ok=True)
with codecs.open(
os.path.join(env.working_dir, file_path),
encoding=env.encoding,
mode='w+'
) as file:
return file.write(content)