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

Allow oneshot commands from the terminal. #208

Merged
merged 2 commits into from
Feb 12, 2024
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
27 changes: 26 additions & 1 deletion mreg_cli/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,18 @@ def main():
metavar="SOURCE",
)

output_args.add_argument(
"--token-only",
dest="token_only",
action="store_true",
default=False,
help="Only attempt token login, this will avoid interactive prompts.",
)

output_args.add_argument(
"command", metavar="command", nargs="*", help="Oneshot command to issue to the cli."
)

args = parser.parse_args()
setup_logging(args.verbosity)
logger.debug(f"args: {args}")
Expand All @@ -135,7 +147,10 @@ def main():
return

try:
try_token_or_login(config.get("user"), config.get("url"))
try_token_or_login(
config.get("user"), config.get("url"), fail_without_token=args.token_only
)

except (EOFError, KeyboardInterrupt, LoginFailedError) as e:
print(e)
raise SystemExit() from None
Expand Down Expand Up @@ -171,6 +186,16 @@ def get_prompt_message():
cli.process_command_line(command)
return

# Check if we got a oneshot command. If so, execute it and exit.
if args.command:
cmd = " ".join(args.command)
try:
cli.process_command_line(cmd)
except ValueError as e:
print(e)

raise SystemExit() from None

# The app runs in an infinite loop and is expected to exit using sys.exit()
while True:
try:
Expand Down
4 changes: 3 additions & 1 deletion mreg_cli/utilities/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ def set_file_permissions(f: str, mode: int) -> None:
pass


def try_token_or_login(user: str, url: str) -> None:
def try_token_or_login(user: str, url: str, fail_without_token: bool = False) -> None:
"""Check for a valid token or interactively log in to MREG.

Exits on connection failure.
Expand Down Expand Up @@ -90,6 +90,8 @@ def try_token_or_login(user: str, url: str) -> None:
error(f"Could not connect to {url}")

if ret.status_code == 401:
if fail_without_token:
raise SystemExit("Token only login failed.")
prompt_for_password_and_login(user, url, catch_exception=False)


Expand Down
Loading