Skip to content
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
43 changes: 43 additions & 0 deletions novem/cli/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
from ..version import __version__
from .common import grid, job, mail, plot, user
from .config import check_if_profile_exists, update_config
from .gql import NovemGQL
from .group import group
from .invite import invite
from .setup import setup
Expand Down Expand Up @@ -392,11 +393,53 @@ def run_cli_wrapped() -> None:

# check info and if present get info
if args and args["info"]:
if args.get("profile"):
args["config_profile"] = args["profile"]
novem = NovemAPI(**args, is_cli=True)
info = novem.read("/admin/profile/overview")
print(info)
return

# handle --gql to run a GraphQL query from stdin, file, or inline
# Only run standalone if no other commands are specified
if args and args.get("gql"):
# Map profile to config_profile for get_current_config
if args.get("profile"):
args["config_profile"] = args["profile"]

gql_arg = args["gql"]
has_other_cmd = (
args.get("plot") != ""
or args.get("grid") != ""
or args.get("mail") != ""
or args.get("job") != ""
or args.get("invite") != ""
or args.get("for_user") != ""
or "org" in args # uses SUPPRESS, so only present if specified
or "group" in args # uses SUPPRESS, so only present if specified
)

# If --gql has a value (@file or inline query), or no other command, run standalone
if isinstance(gql_arg, str) or (gql_arg is True and not has_other_cmd):
import json

if gql_arg is True:
# No argument and no other command - read from stdin
query = sys.stdin.read()
elif gql_arg.startswith("@"):
# Read query from file (expand ~ for home directory)
filename = os.path.expanduser(gql_arg[1:])
with open(filename, "r") as f:
query = f.read()
else:
# Treat as inline query
query = gql_arg

gql = NovemGQL(**args)
result = gql.run_raw_query(query)
print(json.dumps(result, indent=2))
return

# if --fs is set get terminal dimensions and ammend qpr
if args and "fs" in args and args["fs"]:
sz = os.get_terminal_size()
Expand Down
19 changes: 18 additions & 1 deletion novem/cli/gql.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,9 @@ def __init__(self, **kwargs: Any) -> None:
self._config = config
self._session = requests.Session()
self._debug = kwargs.get("debug", False)
self._gql_debug = kwargs.get("gql_debug", False)
# Support both old gql_debug and new gql parameter for debug mode
gql_param = kwargs.get("gql", False)
self._gql_debug = gql_param is True # True when --gql with no argument

token = config.get("token")
if token:
Expand All @@ -41,6 +43,21 @@ def __init__(self, **kwargs: Any) -> None:
if self._debug:
print(f"GQL endpoint: {self._endpoint}")

def run_raw_query(self, query: str, variables: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
"""Execute a GraphQL query and return the raw result (for CLI --gql @filename)."""
payload: Dict[str, Any] = {"query": query}
if variables:
payload["variables"] = variables

if self._debug:
print(f"GQL query: {query.strip()}")
if variables:
print(f"GQL variables: {variables}")

response = self._session.post(self._endpoint, json=payload)
response.raise_for_status()
return response.json()

def _query(self, query: str, variables: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
"""Execute a GraphQL query and return the result."""
payload: Dict[str, Any] = {"query": query}
Expand Down
9 changes: 6 additions & 3 deletions novem/cli/setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,11 +51,14 @@ def setup(raw_args: Any = None) -> Tuple[Any, Dict[str, str]]:

parser.add_argument(
"--gql",
dest="gql_debug",
action="store_true",
dest="gql",
action="store",
required=False,
nargs="?",
const=True,
default=False,
help="Show GraphQL query and response",
help="Run a GraphQL query. Use @filename to read from file, no argument to read from stdin, "
"or combine with -p/-g/-m/-j/-u to show debug output",
)

parser.add_argument(
Expand Down
Loading