Skip to content

Commit 5fb6d8f

Browse files
refactor: adopt EAFP and explicit error handling for password file (#1203)
* refactor: adopt EAFP and explicit error handling for password file Co-authored-by: Roland Walker <[email protected]>
1 parent 2c9ab92 commit 5fb6d8f

File tree

3 files changed

+18
-9
lines changed

3 files changed

+18
-9
lines changed

changelog.md

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,9 @@
1-
Upcoming (TBD)
2-
==============
1+
Upcoming Release (TBD)
2+
======================
33

44
Features
55
--------
6-
6+
* Added explicit error handle to get_password_from_file with EAFP.
77

88
Internal
99
--------

mycli/AUTHORS

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ Contributors:
1515
* Abirami P
1616
* Adam Chainz
1717
* Aljosha Papsch
18+
* Allrob
1819
* Andy Teijelo Pérez
1920
* Angelo Lupo
2021
* Artem Bezsmertnyi

mycli/main.py

Lines changed: 14 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -85,6 +85,9 @@
8585

8686
SUPPORT_INFO = "Home: http://mycli.net\n" "Bug tracker: https://github.com/dbcli/mycli/issues"
8787

88+
class PasswordFileError(Exception):
89+
"""Base exception for errors related to reading password files."""
90+
pass
8891

8992
class MyCli(object):
9093
default_prompt = "\\t \\u@\\h:\\d> "
@@ -536,14 +539,19 @@ def _connect():
536539
sys.exit(1)
537540

538541
def get_password_from_file(self, password_file):
539-
password_from_file = None
540542
if password_file:
541-
if (os.path.isfile(password_file) or stat.S_ISFIFO(os.stat(password_file).st_mode)) and os.access(password_file, os.R_OK):
543+
try:
542544
with open(password_file) as fp:
543-
password_from_file = fp.readline()
544-
password_from_file = password_from_file.rstrip().lstrip()
545-
546-
return password_from_file
545+
password = fp.readline().strip()
546+
return password
547+
except FileNotFoundError:
548+
raise PasswordFileError(f"Password file '{password_file}' not found") from None
549+
except PermissionError:
550+
raise PasswordFileError(f"Permission denied reading password file '{password_file}'") from None
551+
except IsADirectoryError:
552+
raise PasswordFileError(f"Path '{password_file}' is a directory, not a file") from None
553+
except Exception as e:
554+
raise PasswordFileError(f"Error reading password file '{password_file}': {str(e)}") from None
547555

548556
def handle_editor_command(self, text):
549557
r"""Editor command is any query that is prefixed or suffixed by a '\e'.

0 commit comments

Comments
 (0)