Skip to content

Commit

Permalink
Validate settings on edit
Browse files Browse the repository at this point in the history
[noissue]
  • Loading branch information
mdellweg committed May 13, 2021
1 parent d9b514e commit db5b018
Showing 1 changed file with 36 additions and 21 deletions.
57 changes: 36 additions & 21 deletions pulpcore/cli/common/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,26 @@ def validate_config(config: Dict[str, Any], strict: bool = False) -> bool:
return True


def validate_settings(settings: Dict[str, Dict[str, Any]], strict: bool = False) -> bool:
errors: List[str] = []
if "cli" not in settings:
errors.append(_("Could not locate default profile 'cli' setting"))

for key, profile in settings.items():
if key != "cli" and not key.startswith("cli-"):
if strict:
errors.append(_("Invalid profile '{}'").format(key))
continue
try:
validate_config(profile, strict=strict)
except ValueError as e:
errors.append(_("Profile {}:").format(key))
errors.append(str(e))
if errors:
raise ValueError("\n".join(errors))
return True


@click.group(name="config", help=_("Manage pulp-cli config file"))
def config() -> None:
pass
Expand Down Expand Up @@ -137,10 +157,18 @@ def edit(location: str) -> None:
)

with Path(location).open("r+") as sfile:
settings = sfile.read()
output = click.edit(settings)
if not output:
raise click.ClickException("No output from editor. Aborting.")
output = sfile.read()
while True:
output = click.edit(output)
if not output:
raise click.ClickException("No output from editor. Aborting.")
try:
settings = toml.loads(output)
validate_settings(settings)
break
except (ValueError, toml.TomlDecodeError) as e:
click.echo(str(e), err=True)
click.confirm(_("Retry"), abort=True)
sfile.seek(0)
sfile.write(output)

Expand All @@ -154,22 +182,9 @@ def validate(location: str, strict: bool) -> None:
except toml.TomlDecodeError:
raise click.ClickException(_("Invalid toml file '{location}'.").format(location=location))

if "cli" not in settings:
raise click.ClickException(_("Could not locate cli section in '{location}'.").format(location=location))

errors: List[str] = []
for key, profile in settings.items():
if key != "cli" and not key.startswith("cli-"):
if strict:
errors.append(_("Invalid profile '{}'").format(key))
continue
try:
validate_config(profile, strict=strict)
except ValueError as e:
errors.append(_("Profile {}:").format(key))
errors.append(str(e))

if errors:
raise click.ClickException("\n".join(errors))
try:
validate_settings(settings, strict)
except ValueError as e:
raise click.ClickException(str(e))

click.echo(f"File '{location}' is a valid pulp-cli config.")

0 comments on commit db5b018

Please sign in to comment.