Skip to content

Commit 9acba4a

Browse files
authored
Some more s/Python-dotenv/python-dotenv/ (#552)
1 parent 3c19c03 commit 9acba4a

File tree

3 files changed

+47
-50
lines changed

3 files changed

+47
-50
lines changed

.github/SECURITY.md

+2-3
Original file line numberDiff line numberDiff line change
@@ -9,11 +9,10 @@
99

1010
## Reporting a Vulnerability
1111

12-
If you believe you have identified a security issue with Python-dotenv, please email
12+
If you believe you have identified a security issue with python-dotenv, please email
1313
python-dotenv@saurabh-kumar.com. A maintainer will contact you acknowledging the report
1414
and how to continue.
1515

1616
Be sure to include as much detail as necessary in your report. As with reporting normal
1717
issues, a minimal reproducible example will help the maintainers address the issue faster.
18-
If you are able, you may also include a fix for the issue generated with `git
19-
format-patch`.
18+
If you are able, you may also include a fix for the issue generated with `git format-patch`.

src/dotenv/main.py

+25-24
Original file line numberDiff line numberDiff line change
@@ -7,8 +7,7 @@
77
import tempfile
88
from collections import OrderedDict
99
from contextlib import contextmanager
10-
from typing import (IO, Dict, Iterable, Iterator, Mapping, Optional, Tuple,
11-
Union)
10+
from typing import IO, Dict, Iterable, Iterator, Mapping, Optional, Tuple, Union
1211

1312
from .parser import Binding, parse_stream
1413
from .variables import parse_variables
@@ -17,7 +16,7 @@
1716
# These paths may flow to `open()` and `shutil.move()`; `shutil.move()`
1817
# only accepts string paths, not byte paths or file descriptors. See
1918
# https://github.com/python/typeshed/pull/6832.
20-
StrPath = Union[str, 'os.PathLike[str]']
19+
StrPath = Union[str, "os.PathLike[str]"]
2120

2221
logger = logging.getLogger(__name__)
2322

@@ -26,7 +25,7 @@ def with_warn_for_invalid_lines(mappings: Iterator[Binding]) -> Iterator[Binding
2625
for mapping in mappings:
2726
if mapping.error:
2827
logger.warning(
29-
"Python-dotenv could not parse statement starting at line %s",
28+
"python-dotenv could not parse statement starting at line %s",
3029
mapping.original.line,
3130
)
3231
yield mapping
@@ -60,10 +59,10 @@ def _get_stream(self) -> Iterator[IO[str]]:
6059
else:
6160
if self.verbose:
6261
logger.info(
63-
"Python-dotenv could not find configuration file %s.",
64-
self.dotenv_path or '.env',
62+
"python-dotenv could not find configuration file %s.",
63+
self.dotenv_path or ".env",
6564
)
66-
yield io.StringIO('')
65+
yield io.StringIO("")
6766

6867
def dict(self) -> Dict[str, Optional[str]]:
6968
"""Return dotenv as dict"""
@@ -73,7 +72,9 @@ def dict(self) -> Dict[str, Optional[str]]:
7372
raw_values = self.parse()
7473

7574
if self.interpolate:
76-
self._dict = OrderedDict(resolve_variables(raw_values, override=self.override))
75+
self._dict = OrderedDict(
76+
resolve_variables(raw_values, override=self.override)
77+
)
7778
else:
7879
self._dict = OrderedDict(raw_values)
7980

@@ -101,8 +102,7 @@ def set_as_environment_variables(self) -> bool:
101102
return True
102103

103104
def get(self, key: str) -> Optional[str]:
104-
"""
105-
"""
105+
""" """
106106
data = self.dict()
107107

108108
if key in data:
@@ -166,17 +166,16 @@ def set_key(
166166
if quote_mode not in ("always", "auto", "never"):
167167
raise ValueError(f"Unknown quote_mode: {quote_mode}")
168168

169-
quote = (
170-
quote_mode == "always"
171-
or (quote_mode == "auto" and not value_to_set.isalnum())
169+
quote = quote_mode == "always" or (
170+
quote_mode == "auto" and not value_to_set.isalnum()
172171
)
173172

174173
if quote:
175174
value_out = "'{}'".format(value_to_set.replace("'", "\\'"))
176175
else:
177176
value_out = value_to_set
178177
if export:
179-
line_out = f'export {key_to_set}={value_out}\n'
178+
line_out = f"export {key_to_set}={value_out}\n"
180179
else:
181180
line_out = f"{key_to_set}={value_out}\n"
182181

@@ -223,7 +222,9 @@ def unset_key(
223222
dest.write(mapping.original.string)
224223

225224
if not removed:
226-
logger.warning("Key %s not removed from %s - key doesn't exist.", key_to_unset, dotenv_path)
225+
logger.warning(
226+
"Key %s not removed from %s - key doesn't exist.", key_to_unset, dotenv_path
227+
)
227228
return None, key_to_unset
228229

229230
return removed, key_to_unset
@@ -235,7 +236,7 @@ def resolve_variables(
235236
) -> Mapping[str, Optional[str]]:
236237
new_values: Dict[str, Optional[str]] = {}
237238

238-
for (name, value) in values:
239+
for name, value in values:
239240
if value is None:
240241
result = None
241242
else:
@@ -259,7 +260,7 @@ def _walk_to_root(path: str) -> Iterator[str]:
259260
Yield directories starting from the given directory up to the root
260261
"""
261262
if not os.path.exists(path):
262-
raise IOError('Starting path not found')
263+
raise IOError("Starting path not found")
263264

264265
if os.path.isfile(path):
265266
path = os.path.dirname(path)
@@ -273,7 +274,7 @@ def _walk_to_root(path: str) -> Iterator[str]:
273274

274275

275276
def find_dotenv(
276-
filename: str = '.env',
277+
filename: str = ".env",
277278
raise_error_if_not_found: bool = False,
278279
usecwd: bool = False,
279280
) -> str:
@@ -284,14 +285,14 @@ def find_dotenv(
284285
"""
285286

286287
def _is_interactive():
287-
""" Decide whether this is running in a REPL or IPython notebook """
288+
"""Decide whether this is running in a REPL or IPython notebook"""
288289
try:
289-
main = __import__('__main__', None, None, fromlist=['__file__'])
290+
main = __import__("__main__", None, None, fromlist=["__file__"])
290291
except ModuleNotFoundError:
291292
return False
292-
return not hasattr(main, '__file__')
293+
return not hasattr(main, "__file__")
293294

294-
if usecwd or _is_interactive() or getattr(sys, 'frozen', False):
295+
if usecwd or _is_interactive() or getattr(sys, "frozen", False):
295296
# Should work without __file__, e.g. in REPL or IPython notebook.
296297
path = os.getcwd()
297298
else:
@@ -313,9 +314,9 @@ def _is_interactive():
313314
return check_path
314315

315316
if raise_error_if_not_found:
316-
raise IOError('File not found')
317+
raise IOError("File not found")
317318

318-
return ''
319+
return ""
319320

320321

321322
def load_dotenv(

tests/test_main.py

+20-23
Original file line numberDiff line numberDiff line change
@@ -28,9 +28,9 @@ def test_set_key_no_file(tmp_path):
2828
("", "a", "", (True, "a", ""), "a=''\n"),
2929
("", "a", "b", (True, "a", "b"), "a='b'\n"),
3030
("", "a", "'b'", (True, "a", "'b'"), "a='\\'b\\''\n"),
31-
("", "a", "\"b\"", (True, "a", '"b"'), "a='\"b\"'\n"),
31+
("", "a", '"b"', (True, "a", '"b"'), "a='\"b\"'\n"),
3232
("", "a", "b'c", (True, "a", "b'c"), "a='b\\'c'\n"),
33-
("", "a", "b\"c", (True, "a", "b\"c"), "a='b\"c'\n"),
33+
("", "a", 'b"c', (True, "a", 'b"c'), "a='b\"c'\n"),
3434
("a=b", "a", "c", (True, "a", "c"), "a='c'\n"),
3535
("a=b\n", "a", "c", (True, "a", "c"), "a='c'\n"),
3636
("a=b\n\n", "a", "c", (True, "a", "c"), "a='c'\n\n"),
@@ -75,20 +75,20 @@ def test_get_key_no_file(tmp_path):
7575
nx_path = tmp_path / "nx"
7676
logger = logging.getLogger("dotenv.main")
7777

78-
with mock.patch.object(logger, "info") as mock_info, \
79-
mock.patch.object(logger, "warning") as mock_warning:
78+
with (
79+
mock.patch.object(logger, "info") as mock_info,
80+
mock.patch.object(logger, "warning") as mock_warning,
81+
):
8082
result = dotenv.get_key(nx_path, "foo")
8183

8284
assert result is None
8385
mock_info.assert_has_calls(
8486
calls=[
85-
mock.call("Python-dotenv could not find configuration file %s.", nx_path)
87+
mock.call("python-dotenv could not find configuration file %s.", nx_path)
8688
],
8789
)
8890
mock_warning.assert_has_calls(
89-
calls=[
90-
mock.call("Key %s not found in %s.", "foo", nx_path)
91-
],
91+
calls=[mock.call("Key %s not found in %s.", "foo", nx_path)],
9292
)
9393

9494

@@ -249,10 +249,12 @@ def test_load_dotenv_no_file_verbose():
249249
logger = logging.getLogger("dotenv.main")
250250

251251
with mock.patch.object(logger, "info") as mock_info:
252-
result = dotenv.load_dotenv('.does_not_exist', verbose=True)
252+
result = dotenv.load_dotenv(".does_not_exist", verbose=True)
253253

254254
assert result is False
255-
mock_info.assert_called_once_with("Python-dotenv could not find configuration file %s.", ".does_not_exist")
255+
mock_info.assert_called_once_with(
256+
"python-dotenv could not find configuration file %s.", ".does_not_exist"
257+
)
256258

257259

258260
@mock.patch.dict(os.environ, {"a": "c"}, clear=True)
@@ -317,21 +319,23 @@ def test_load_dotenv_file_stream(dotenv_path):
317319

318320

319321
def test_load_dotenv_in_current_dir(tmp_path):
320-
dotenv_path = tmp_path / '.env'
321-
dotenv_path.write_bytes(b'a=b')
322-
code_path = tmp_path / 'code.py'
323-
code_path.write_text(textwrap.dedent("""
322+
dotenv_path = tmp_path / ".env"
323+
dotenv_path.write_bytes(b"a=b")
324+
code_path = tmp_path / "code.py"
325+
code_path.write_text(
326+
textwrap.dedent("""
324327
import dotenv
325328
import os
326329
327330
dotenv.load_dotenv(verbose=True)
328331
print(os.environ['a'])
329-
"""))
332+
""")
333+
)
330334
os.chdir(tmp_path)
331335

332336
result = sh.Command(sys.executable)(code_path)
333337

334-
assert result == 'b\n'
338+
assert result == "b\n"
335339

336340

337341
def test_dotenv_values_file(dotenv_path):
@@ -352,30 +356,23 @@ def test_dotenv_values_file(dotenv_path):
352356
({"b": "c"}, "a=${b}", True, {"a": "c"}),
353357
({"b": "c"}, "a=${b:-d}", False, {"a": "${b:-d}"}),
354358
({"b": "c"}, "a=${b:-d}", True, {"a": "c"}),
355-
356359
# Defined in file
357360
({}, "b=c\na=${b}", True, {"a": "c", "b": "c"}),
358-
359361
# Undefined
360362
({}, "a=${b}", True, {"a": ""}),
361363
({}, "a=${b:-d}", True, {"a": "d"}),
362-
363364
# With quotes
364365
({"b": "c"}, 'a="${b}"', True, {"a": "c"}),
365366
({"b": "c"}, "a='${b}'", True, {"a": "c"}),
366-
367367
# With surrounding text
368368
({"b": "c"}, "a=x${b}y", True, {"a": "xcy"}),
369-
370369
# Self-referential
371370
({"a": "b"}, "a=${a}", True, {"a": "b"}),
372371
({}, "a=${a}", True, {"a": ""}),
373372
({"a": "b"}, "a=${a:-c}", True, {"a": "b"}),
374373
({}, "a=${a:-c}", True, {"a": "c"}),
375-
376374
# Reused
377375
({"b": "c"}, "a=${b}${b}", True, {"a": "cc"}),
378-
379376
# Re-defined and used in file
380377
({"b": "c"}, "b=d\na=${b}", True, {"a": "d", "b": "d"}),
381378
({}, "a=b\na=c\nd=${a}", True, {"a": "c", "d": "c"}),

0 commit comments

Comments
 (0)