Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix for expanding dot env variables in scripts #4979

Merged
merged 7 commits into from
Mar 12, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions news/4975.bugfix.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Environment variables from dot env files are now properly expanded when included in scripts.
26 changes: 12 additions & 14 deletions pipenv/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -103,25 +103,23 @@ def load_dot_env(project, as_dict=False):
[project_directory, ".env"]
)

if os.path.isfile(dotenv_file):
if not os.path.isfile(dotenv_file) and project.s.PIPENV_DOTENV_LOCATION:
click.echo(
crayons.normal(fix_utf8("Loading .env environment variables..."), bold=True),
"{}: file {}={} does not exist!!\n{}".format(
crayons.red("Warning", bold=True),
crayons.normal("PIPENV_DOTENV_LOCATION", bold=True),
crayons.normal(project.s.PIPENV_DOTENV_LOCATION, bold=True),
crayons.red("Not loading environment variables.", bold=True),
),
oz123 marked this conversation as resolved.
Show resolved Hide resolved
err=True,
)
else:
if project.s.PIPENV_DOTENV_LOCATION:
click.echo(
"{}: file {}={} does not exist!!\n{}".format(
crayons.red("Warning", bold=True),
crayons.normal("PIPENV_DOTENV_LOCATION", bold=True),
crayons.normal(project.s.PIPENV_DOTENV_LOCATION, bold=True),
crayons.red("Not loading environment variables.", bold=True),
),
err=True,
)
if as_dict:
return dotenv.dotenv_values(dotenv_file)
else:
click.echo(
crayons.normal(fix_utf8("Loading .env environment variables..."), bold=True),
err=False,
)
dotenv.load_dotenv(dotenv_file, override=True)
project.s.initialize()

Expand Down Expand Up @@ -2473,8 +2471,8 @@ def do_run(project, command, args, three=None, python=False, pypi_mirror=None):
project, three=three, python=python, validate=False, pypi_mirror=pypi_mirror,
)

load_dot_env(project)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I am afraid this will break the isolation in test cases. dotenv files in one test case will contaminate other cases env.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@frostming Could you elaborate on this? Right now the test suite is passing with this change so I am not sure I understand, but maybe I do. If its a testing concern, shouldn't it be on a top level test fixture to cleanup the environment before or after each test?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The issue without this change is that environment that gets used for running the script is the environment without the dotenv variables. Is there a better way to accomplish it?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

shouldn't it be on a top level test fixture to cleanup the environment before or after each test?

Oh yeah, it is cleaned up.

env = os.environ.copy()
env.update(load_dot_env(project, as_dict=True) or {})
env.pop("PIP_SHIMS_BASE_MODULE", None)

path = env.get('PATH', '')
Expand Down
21 changes: 21 additions & 0 deletions tests/integration/test_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -210,6 +210,27 @@ def test_scripts(PipenvInstance):
assert 'which python' in c.stdout


@pytest.mark.cli
def test_scripts_resolve_dot_env_vars(PipenvInstance):
with PipenvInstance() as p:
with open(".env", "w") as f:
contents = """
HELLO=WORLD
""".strip()
f.write(contents)

with open(p.pipfile_path, "w") as f:
contents = """
[scripts]
hello = "echo $HELLO"
""".strip()
f.write(contents)
c = p.pipenv('run hello')
print(c)
print(c.stdout)
assert 'WORLD' in c.stdout


@pytest.mark.cli
def test_help(PipenvInstance):
with PipenvInstance() as p:
Expand Down
4 changes: 2 additions & 2 deletions tests/integration/test_lock.py
Original file line number Diff line number Diff line change
Expand Up @@ -457,7 +457,7 @@ def test_outdated_setuptools_with_pep517_legacy_build_meta_is_updated(PipenvInst
assert c.returncode == 0
c = p.pipenv("run python -c 'import setuptools; print(setuptools.__version__)'")
assert c.returncode == 0
assert c.stdout.strip() == "40.2.0"
assert c.stdout.splitlines()[1] == "40.2.0"
c = p.pipenv("install legacy-backend-package")
assert c.returncode == 0
assert "vistir" in p.lockfile["default"]
Expand All @@ -481,7 +481,7 @@ def test_outdated_setuptools_with_pep517_cython_import_in_setuppy(PipenvInstance
assert c.returncode == 0
c = p.pipenv("run python -c 'import setuptools; print(setuptools.__version__)'")
assert c.returncode == 0
assert c.stdout.strip() == "40.2.0"
assert c.stdout.splitlines()[1] == "40.2.0"
c = p.pipenv("install cython-import-package")
assert c.returncode == 0
assert "vistir" in p.lockfile["default"]
Expand Down
4 changes: 2 additions & 2 deletions tests/integration/test_project.py
Original file line number Diff line number Diff line change
Expand Up @@ -189,7 +189,7 @@ def test_run_in_virtualenv_with_global_context(PipenvInstance, virtualenv):

c = p.pipenv("run python -c 'import click;print(click.__file__)'")
assert c.returncode == 0, (c.stdout, c.stderr)
assert is_in_path(c.stdout.strip(), str(virtualenv)), (c.stdout.strip(), str(virtualenv))
assert is_in_path(c.stdout.splitlines()[1], str(virtualenv)), (c.stdout.splitlines()[1], str(virtualenv))

c = p.pipenv("clean --dry-run")
assert c.returncode == 0, (c.stdout, c.stderr)
Expand All @@ -210,7 +210,7 @@ def test_run_in_virtualenv(PipenvInstance):
assert c.returncode == 0
c = p.pipenv('run python -c "import click;print(click.__file__)"')
assert c.returncode == 0
assert normalize_path(c.stdout.strip()).startswith(
assert normalize_path(c.stdout.splitlines()[1]).startswith(
normalize_path(str(project.virtualenv_location))
)
c = p.pipenv("clean --dry-run")
Expand Down
8 changes: 4 additions & 4 deletions tests/integration/test_run.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,12 +36,12 @@ def test_scripts(PipenvInstance):
assert c.returncode == 0
c = p.pipenv('run printfoo')
assert c.returncode == 0
assert c.stdout.splitlines()[0] == 'foo'
assert c.stdout.splitlines()[1] == 'foo'
assert not c.stderr.strip()

c = p.pipenv('run notfoundscript')
assert c.returncode != 0
assert c.stdout == ''
assert c.stdout == 'Loading .env environment variables...\n'
if os.name != 'nt': # TODO: Implement this message for Windows.
assert 'not found' in c.stderr

Expand All @@ -60,7 +60,7 @@ def test_scripts(PipenvInstance):
c = p.pipenv("run scriptwithenv")
assert c.returncode == 0
if os.name != "nt": # This doesn't work on CI windows.
assert c.stdout.strip() == "WORLD"
assert c.stdout.splitlines()[1] == "WORLD"


@pytest.mark.run
Expand All @@ -80,5 +80,5 @@ def test_run_with_usr_env_shebang(PipenvInstance):
c = p.pipenv("run ./test_script")
assert c.returncode == 0
project = Project()
lines = [line.strip() for line in c.stdout.splitlines()]
lines = [line.strip() for line in c.stdout.splitlines()[1:]]
assert all(line == project.virtualenv_location for line in lines)