Skip to content

Commit

Permalink
output: Add new output mode: cmd.
Browse files Browse the repository at this point in the history
This new output is thought to be used when executing a command in a VM/VMSS.
It permits to print the output of the command like if this was executed locally.

Signed-off-by: Francis Laniel <[email protected]>
  • Loading branch information
eiffel-fl committed Jan 16, 2023
1 parent 11f2454 commit 162e599
Showing 1 changed file with 33 additions and 0 deletions.
33 changes: 33 additions & 0 deletions knack/output.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
import traceback
from collections import OrderedDict
from io import StringIO
import sys

from .events import EVENT_INVOKER_POST_PARSE_ARGS, EVENT_PARSER_GLOBAL_CREATE
from .log import get_logger
Expand All @@ -30,6 +31,37 @@ def default(self, o): # pylint: disable=method-hidden
return json.JSONEncoder.default(self, o)


def format_cmd(obj):
result = obj.result
if 'value' not in result:
raise CLIError(f"result ({result}) does not contain key 'value'. "
"Are you sure to use cmd output for the corresponding az command?")

value = result['value'][0]
if 'message' not in value:
raise CLIError(f"value ({value}) does not contain key 'message'. "
"Are you sure to use cmd output for the corresponding az command?")

message = value['message']

stdout_begin = message.find("[stdout]\n")
stderr_begin = message.find("[stderr]\n")
if stdout_begin == -1 or stderr_begin == -1:
raise CLIError(f"message ({message}) does not contain 'stdout' or stderr. "
"Are you sure to use cmd output for the corresponding az command?")

stdout_begin += len("[stdout]\n")
# We remove two to avoid the last \n.
stderr_output = message[stdout_begin:stderr_begin - 2]

stderr_begin += len("[stderr]\n")
stdout_output = message[stderr_begin:-2]

print(stderr_output, file=sys.stderr)

return stdout_output


def format_json(obj):
result = obj.result
# OrderedDict.__dict__ is always '{}', to persist the data, convert to dict first.
Expand Down Expand Up @@ -99,6 +131,7 @@ class OutputProducer(object):
'table': format_table,
'tsv': format_tsv,
'none': format_none,
'cmd': format_cmd,
}

@staticmethod
Expand Down

0 comments on commit 162e599

Please sign in to comment.