Skip to content

Commit

Permalink
Refactor to not check file existence, and open in only one place
Browse files Browse the repository at this point in the history
  • Loading branch information
oprypin committed Jun 27, 2021
1 parent 9776d0e commit 92f3da0
Showing 1 changed file with 24 additions and 19 deletions.
43 changes: 24 additions & 19 deletions mkdocs/config/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -156,29 +156,34 @@ def _open_config_file(config_file):

# Default to the standard config filename.
if config_file is None:
for possible_file_ending in ('yml', 'yaml'):
config_file = os.path.abspath('mkdocs.{}'.format(possible_file_ending))
if os.path.exists(config_file):
break
else:
config_file = os.path.abspath('mkdocs.yml')

# If closed file descriptor, get file path to reopen later.
if hasattr(config_file, 'closed') and config_file.closed:
config_file = config_file.name

log.debug(f"Loading configuration file: {config_file}")

paths_to_try = ['mkdocs.yml', 'mkdocs.yaml']
# If it is a string, we can assume it is a path and attempt to open it.
if isinstance(config_file, str):
if os.path.exists(config_file):
config_file = open(config_file, 'rb')
elif isinstance(config_file, str):
paths_to_try = [config_file]
# If closed file descriptor, get file path to reopen later.
elif getattr(config_file, 'closed', False):
paths_to_try = [config_file.name]
else:
paths_to_try = None

if paths_to_try:
# config_file is not a file descriptor, so open it as a path.
for path in paths_to_try:
path = os.path.abspath(path)
log.debug(f"Loading configuration file: {path}")
try:
config_file = open(path, 'rb')
break
except FileNotFoundError:
continue
else:
raise exceptions.ConfigurationError(
f"Config file '{config_file}' does not exist.")
f"Config file '{paths_to_try[0]}' does not exist.")
else:
log.debug(f"Loading configuration file: {config_file}")
# Ensure file descriptor is at begining
config_file.seek(0)

# Ensure file descriptor is at begining
config_file.seek(0)
try:
yield config_file
finally:
Expand Down

0 comments on commit 92f3da0

Please sign in to comment.