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

feature: Add get options to cli for interface with get_credential and support JSON output #678

Merged
merged 15 commits into from
Apr 26, 2024
Merged
55 changes: 50 additions & 5 deletions keyring/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import argparse
import getpass
import json
import sys

from . import (
Expand All @@ -12,6 +13,7 @@
get_password,
set_keyring,
set_password,
get_credential,
)
from .util import platform_

Expand Down Expand Up @@ -41,6 +43,32 @@ def __init__(self):
self.parser.add_argument(
"--disable", action="store_true", help="Disable keyring and exit"
)
self.parser._get_modes = ["password", "creds"]
self.parser.add_argument(
"--mode",
choices=self.parser._get_modes,
dest="get_mode",
default="password",
help="""
Mode for 'get' operation.
'password' requires a username and will return only the password.
'creds' does not require a username and will return both the username and password separated by a newline.

Default is 'password'
""",
)
self.parser._output_formats = ["plain", "json"]
self.parser.add_argument(
"--output",
choices=self.parser._output_formats,
dest="output_format",
default="plain",
help="""
Output format for 'get' operation.

Default is 'plain'
""",
)
self.parser._operations = ["get", "set", "del", "diagnose"]
self.parser.add_argument(
'operation',
Expand Down Expand Up @@ -81,14 +109,31 @@ def run(self, argv):

def _check_args(self):
if self.operation:
if self.service is None or self.username is None:
if self.operation == 'get' and self.get_mode == 'creds':
if self.service is None:
self.parser.error(f"{self.operation} requires service")
elif self.service is None or self.username is None:
self.parser.error(f"{self.operation} requires service and username")
jaraco marked this conversation as resolved.
Show resolved Hide resolved

def do_get(self):
password = get_password(self.service, self.username)
if password is None:
raise SystemExit(1)
print(password)
credential_dict = {}
if self.get_mode == 'creds':
creds = get_credential(self.service, self.username)
if creds is None:
raise SystemExit(1)
credential_dict['username'] = creds.username
credential_dict['password'] = creds.password
else:
password = get_password(self.service, self.username)
if password is None:
raise SystemExit(1)
credential_dict['password'] = password
if self.output_format == 'json':
print(json.dumps(credential_dict))
else:
if 'username' in credential_dict.keys():
print(credential_dict['username'])
print(credential_dict['password'])

def do_set(self):
password = self.input_password(
Expand Down
Loading