Skip to content

Commit b6cf93b

Browse files
committed
Debug
1 parent 49d6d94 commit b6cf93b

File tree

1 file changed

+67
-40
lines changed

1 file changed

+67
-40
lines changed

src/dotenv/cli.py

Lines changed: 67 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import subprocess
12
import json
23
import os
34
import shlex
@@ -8,8 +9,10 @@
89
try:
910
import click
1011
except ImportError:
11-
sys.stderr.write('It seems python-dotenv is not installed with cli option. \n'
12-
'Run pip install "python-dotenv[cli]" to fix this.')
12+
sys.stderr.write(
13+
"It seems python-dotenv is not installed with cli option. \n"
14+
'Run pip install "python-dotenv[cli]" to fix this.'
15+
)
1316
sys.exit(1)
1417

1518
from .main import dotenv_values, set_key, unset_key
@@ -26,25 +29,37 @@ def enumerate_env() -> Optional[str]:
2629
cwd = os.getcwd()
2730
except FileNotFoundError:
2831
return None
29-
path = os.path.join(cwd, '.env')
32+
path = os.path.join(cwd, ".env")
3033
return path
3134

3235

3336
@click.group()
34-
@click.option('-f', '--file', default=enumerate_env(),
35-
type=click.Path(file_okay=True),
36-
help="Location of the .env file, defaults to .env file in current working directory.")
37-
@click.option('-q', '--quote', default='always',
38-
type=click.Choice(['always', 'never', 'auto']),
39-
help="Whether to quote or not the variable values. Default mode is always. This does not affect parsing.")
40-
@click.option('-e', '--export', default=False,
41-
type=click.BOOL,
42-
help="Whether to write the dot file as an executable bash script.")
37+
@click.option(
38+
"-f",
39+
"--file",
40+
default=enumerate_env(),
41+
type=click.Path(file_okay=True),
42+
help="Location of the .env file, defaults to .env file in current working directory.",
43+
)
44+
@click.option(
45+
"-q",
46+
"--quote",
47+
default="always",
48+
type=click.Choice(["always", "never", "auto"]),
49+
help="Whether to quote or not the variable values. Default mode is always. This does not affect parsing.",
50+
)
51+
@click.option(
52+
"-e",
53+
"--export",
54+
default=False,
55+
type=click.BOOL,
56+
help="Whether to write the dot file as an executable bash script.",
57+
)
4358
@click.version_option(version=__version__)
4459
@click.pass_context
4560
def cli(ctx: click.Context, file: Any, quote: Any, export: Any) -> None:
4661
"""This script is used to set, get or unset values from a .env file."""
47-
ctx.obj = {'QUOTE': quote, 'EXPORT': export, 'FILE': file}
62+
ctx.obj = {"QUOTE": quote, "EXPORT": export, "FILE": file}
4863

4964

5065
@contextmanager
@@ -65,51 +80,54 @@ def stream_file(path: os.PathLike) -> Iterator[IO[str]]:
6580

6681
@cli.command()
6782
@click.pass_context
68-
@click.option('--format', default='simple',
69-
type=click.Choice(['simple', 'json', 'shell', 'export']),
70-
help="The format in which to display the list. Default format is simple, "
71-
"which displays name=value without quotes.")
83+
@click.option(
84+
"--format",
85+
default="simple",
86+
type=click.Choice(["simple", "json", "shell", "export"]),
87+
help="The format in which to display the list. Default format is simple, "
88+
"which displays name=value without quotes.",
89+
)
7290
def list(ctx: click.Context, format: bool) -> None:
7391
"""Display all the stored key/value."""
74-
file = ctx.obj['FILE']
92+
file = ctx.obj["FILE"]
7593

7694
with stream_file(file) as stream:
7795
values = dotenv_values(stream=stream)
7896

79-
if format == 'json':
97+
if format == "json":
8098
click.echo(json.dumps(values, indent=2, sort_keys=True))
8199
else:
82-
prefix = 'export ' if format == 'export' else ''
100+
prefix = "export " if format == "export" else ""
83101
for k in sorted(values):
84102
v = values[k]
85103
if v is not None:
86-
if format in ('export', 'shell'):
104+
if format in ("export", "shell"):
87105
v = shlex.quote(v)
88-
click.echo(f'{prefix}{k}={v}')
106+
click.echo(f"{prefix}{k}={v}")
89107

90108

91109
@cli.command()
92110
@click.pass_context
93-
@click.argument('key', required=True)
94-
@click.argument('value', required=True)
111+
@click.argument("key", required=True)
112+
@click.argument("value", required=True)
95113
def set(ctx: click.Context, key: Any, value: Any) -> None:
96114
"""Store the given key/value."""
97-
file = ctx.obj['FILE']
98-
quote = ctx.obj['QUOTE']
99-
export = ctx.obj['EXPORT']
115+
file = ctx.obj["FILE"]
116+
quote = ctx.obj["QUOTE"]
117+
export = ctx.obj["EXPORT"]
100118
success, key, value = set_key(file, key, value, quote, export)
101119
if success:
102-
click.echo(f'{key}={value}')
120+
click.echo(f"{key}={value}")
103121
else:
104122
exit(1)
105123

106124

107125
@cli.command()
108126
@click.pass_context
109-
@click.argument('key', required=True)
127+
@click.argument("key", required=True)
110128
def get(ctx: click.Context, key: Any) -> None:
111129
"""Retrieve the value for the given key."""
112-
file = ctx.obj['FILE']
130+
file = ctx.obj["FILE"]
113131

114132
with stream_file(file) as stream:
115133
values = dotenv_values(stream=stream)
@@ -123,33 +141,32 @@ def get(ctx: click.Context, key: Any) -> None:
123141

124142
@cli.command()
125143
@click.pass_context
126-
@click.argument('key', required=True)
144+
@click.argument("key", required=True)
127145
def unset(ctx: click.Context, key: Any) -> None:
128146
"""Removes the given key."""
129-
file = ctx.obj['FILE']
130-
quote = ctx.obj['QUOTE']
147+
file = ctx.obj["FILE"]
148+
quote = ctx.obj["QUOTE"]
131149
success, key = unset_key(file, key, quote)
132150
if success:
133151
click.echo(f"Successfully removed {key}")
134152
else:
135153
exit(1)
136154

137155

138-
@cli.command(context_settings={'ignore_unknown_options': True})
156+
@cli.command(context_settings={"ignore_unknown_options": True})
139157
@click.pass_context
140158
@click.option(
141159
"--override/--no-override",
142160
default=True,
143161
help="Override variables from the environment file with those from the .env file.",
144162
)
145-
@click.argument('commandline', nargs=-1, type=click.UNPROCESSED)
163+
@click.argument("commandline", nargs=-1, type=click.UNPROCESSED)
146164
def run(ctx: click.Context, override: bool, commandline: List[str]) -> None:
147165
"""Run command with environment variables present."""
148-
file = ctx.obj['FILE']
166+
file = ctx.obj["FILE"]
149167
if not os.path.isfile(file):
150168
raise click.BadParameter(
151-
f'Invalid value for \'-f\' "{file}" does not exist.',
152-
ctx=ctx
169+
f"Invalid value for '-f' \"{file}\" does not exist.", ctx=ctx
153170
)
154171
dotenv_as_dict = {
155172
k: v
@@ -158,7 +175,7 @@ def run(ctx: click.Context, override: bool, commandline: List[str]) -> None:
158175
}
159176

160177
if not commandline:
161-
click.echo('No command given.')
178+
click.echo("No command given.")
162179
exit(1)
163180
run_command(commandline, dotenv_as_dict)
164181

@@ -187,4 +204,14 @@ def run_command(command: List[str], env: Dict[str, str]) -> None:
187204
cmd_env = os.environ.copy()
188205
cmd_env.update(env)
189206

190-
os.execvpe(command[0], args=command, env=cmd_env)
207+
# # os.execvpe(command[0], args=command, env=cmd_env) # Original line
208+
result = subprocess.run(
209+
command, env=cmd_env, capture_output=True, text=True
210+
) # Debug: replace execvpe
211+
if result.returncode != 0: # Debug: check return code
212+
print(f"Subprocess failed with return code: {result.returncode}") # Debug
213+
print(f"Stdout: {result.stdout}") # Debug
214+
print(f"Stderr: {result.stderr}") # Debug
215+
exit(result.returncode) # Debug: exit with subprocess return code
216+
else:
217+
exit(0) # Debug: exit with success if subprocess ok.

0 commit comments

Comments
 (0)