Skip to content

Commit 7cf3c0a

Browse files
committed
minor fix
1 parent 0cf60fd commit 7cf3c0a

File tree

2 files changed

+70
-101
lines changed

2 files changed

+70
-101
lines changed

src/azure-cli-core/azure/cli/core/commands/__init__.py

Lines changed: 24 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -706,16 +706,29 @@ def _what_if(self, args):
706706
if not self._is_command_supported_for_what_if(args):
707707
error_msg = ("\"--what-if\" argument is not supported for this command.")
708708
logger.error(error_msg)
709+
telemetry.set_user_fault(summary='what-if-unsupported-command')
710+
telemetry.set_failure(summary='what-if-unsupported-command')
709711
return CommandResultItem(None, exit_code=1, error=CLIError(error_msg))
710712

711713
from azure.cli.core.what_if import show_what_if
714+
715+
# Remove both --what-if and --export-bicep from args for processing
716+
clean_args = [arg for arg in args if arg not in ['--what-if', '--export-bicep']]
717+
command_parts = [arg for arg in clean_args if not arg.startswith('-') and arg != 'az']
718+
command_name = ' '.join(command_parts) if command_parts else 'unknown'
719+
720+
# Check if --export-bicep is present
721+
export_bicep = '--export-bicep' in args
722+
safe_params = AzCliCommandInvoker._extract_parameter_names(args)
723+
724+
telemetry.set_command_details(
725+
command_name + ' --what-if',
726+
self.data.get('output', 'json'),
727+
safe_params
728+
)
729+
telemetry.set_custom_properties('what-if', 'export_bicep', str(export_bicep))
730+
712731
try:
713-
# Check if --export-bicep is present
714-
export_bicep = '--export-bicep' in args
715-
716-
# Remove both --what-if and --export-bicep from args for processing
717-
clean_args = [arg for arg in args if arg not in ['--what-if', '--export-bicep']]
718-
719732
if export_bicep:
720733
logger.debug("Export bicep mode enabled")
721734

@@ -747,23 +760,25 @@ def _what_if(self, args):
747760
for file_path in bicep_files:
748761
print_styled_text((Style.WARNING, f" {file_path}"))
749762
print("")
763+
telemetry.set_custom_properties('what-if', 'bicep_files_count', str(len(bicep_files)))
750764

751765
# Ensure output format is set for proper formatting
752766
# Default to 'json' if not already set
753767
if 'output' not in self.cli_ctx.invocation.data or self.cli_ctx.invocation.data['output'] is None:
754768
self.cli_ctx.invocation.data['output'] = 'json'
755769

756-
# Return the formatted what-if output as the result
757-
# Similar to the normal flow in execute() method
770+
telemetry.set_success(summary='what-if-completed')
771+
758772
return CommandResultItem(
759773
what_if_result,
760774
table_transformer=None,
761775
is_query_active=self.data.get('query_active', False),
762776
exit_code=0
763777
)
764778
except (CLIError, ValueError, KeyError) as ex:
765-
# If what-if service fails, still show an informative message
766779
logger.error("What-if preview failed: %s", str(ex))
780+
telemetry.set_exception(ex, fault_type='what-if-error', summary=str(ex)[:100])
781+
telemetry.set_failure(summary='what-if-failed')
767782
return CommandResultItem(None, exit_code=1,
768783
error=CLIError(f'What-if preview failed: {str(ex)}'))
769784

src/azure-cli-core/azure/cli/core/what_if.py

Lines changed: 46 additions & 92 deletions
Original file line numberDiff line numberDiff line change
@@ -43,96 +43,54 @@ def _get_auth_headers(cli_ctx, subscription_id):
4343

4444

4545
def _make_what_if_request(payload, headers_dict, cli_ctx=None):
46+
from azure.cli.core.commands.progress import IndeterminateProgressBar
47+
import os
48+
4649
request_completed = threading.Event()
47-
progress_lock = threading.Lock()
48-
49-
def _rotating_progress():
50-
"""Simulate a rotating progress indicator."""
51-
spinner_chars = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"]
52-
fallback_chars = ["|", "\\", "/", "-"]
53-
54-
try:
55-
"⠋".encode(sys.stderr.encoding or 'utf-8')
56-
chars = spinner_chars
57-
except (UnicodeEncodeError, UnicodeDecodeError, LookupError):
58-
chars = fallback_chars
59-
60-
use_color = cli_ctx and getattr(cli_ctx, 'enable_color', False)
61-
if use_color:
62-
try:
63-
CYAN = '\033[36m'
64-
GREEN = '\033[32m'
65-
YELLOW = '\033[33m'
66-
BLUE = '\033[34m'
67-
RESET = '\033[0m'
68-
BOLD = '\033[1m'
69-
except (UnicodeError, AttributeError):
70-
use_color = False
71-
72-
if not use_color:
73-
CYAN = GREEN = YELLOW = BLUE = RESET = BOLD = ''
74-
75-
idx = 0
50+
progress_bar = None
51+
52+
disable_progress = os.environ.get('AZURE_CLI_DISABLE_PROGRESS_BAR') or \
53+
(cli_ctx and cli_ctx.config.getboolean('core', 'disable_progress_bar', False))
54+
55+
def _update_progress():
56+
"""Update progress with different status messages."""
57+
if disable_progress or not progress_bar:
58+
return
59+
7660
start_time = time.time()
61+
messages = [
62+
(0, "Connecting to what-if service"),
63+
(10, "Analyzing Azure CLI script"),
64+
(30, "Processing what-if analysis"),
65+
(60, "Finalizing results")
66+
]
7767

78-
is_tty = hasattr(sys.stderr, 'isatty') and sys.stderr.isatty()
79-
80-
if not is_tty:
81-
sys.stderr.write("Processing")
82-
sys.stderr.flush()
83-
while not request_completed.is_set():
84-
if request_completed.wait(timeout=1.0):
85-
break
86-
sys.stderr.write(".")
87-
sys.stderr.flush()
88-
sys.stderr.write(" Done\n")
89-
sys.stderr.flush()
90-
return
91-
92-
last_line_length = 0
68+
current_message_idx = 0
9369
while not request_completed.is_set():
9470
elapsed = time.time() - start_time
95-
if elapsed < 10:
96-
status = f"{CYAN}Connecting to what-if service{RESET}"
97-
spinner_color = CYAN
98-
elif elapsed < 30:
99-
status = f"{BLUE}Analyzing Azure CLI script{RESET}"
100-
spinner_color = BLUE
101-
elif elapsed < 60:
102-
status = f"{YELLOW}Processing what-if analysis{RESET}"
103-
spinner_color = YELLOW
104-
else:
105-
status = f"{GREEN}Finalizing results{RESET}"
106-
spinner_color = GREEN
107-
elapsed_str = f"{BOLD}({elapsed:.0f}s){RESET}"
108-
spinner = f"{spinner_color}{chars[idx % len(chars)]}{RESET}"
109-
progress_line = f"{spinner} {status}... {elapsed_str}"
110-
visible_length = len(progress_line) - (progress_line.count('\033[') * 5)
111-
max_width = 100
112-
if visible_length > max_width:
113-
truncated_status = status[:max_width - 30] + "..."
114-
progress_line = f"{spinner} {truncated_status} {elapsed_str}"
11571

116-
with progress_lock:
117-
clear_spaces = ' ' * max(last_line_length, 120)
118-
sys.stderr.write(f"\r{clear_spaces}\r{progress_line}")
119-
sys.stderr.flush()
120-
last_line_length = len(progress_line)
72+
for idx, (threshold, message) in enumerate(messages):
73+
if elapsed >= threshold and idx > current_message_idx:
74+
current_message_idx = idx
75+
try:
76+
progress_bar.update_progress_with_msg(message)
77+
except:
78+
pass
12179

122-
idx += 1
123-
if request_completed.wait(timeout=0.12):
80+
if request_completed.wait(timeout=1.0):
12481
break
125-
126-
with progress_lock:
127-
if is_tty:
128-
clear_spaces = ' ' * max(last_line_length, 120)
129-
sys.stderr.write(f"\r{clear_spaces}\r")
130-
sys.stderr.flush()
13182

13283
try:
13384
function_app_url = "https://azcli-script-insight.azurewebsites.net"
13485

135-
progress_thread = threading.Thread(target=_rotating_progress)
86+
if not disable_progress and cli_ctx:
87+
try:
88+
progress_bar = IndeterminateProgressBar(cli_ctx, message="Connecting to what-if service")
89+
progress_bar.begin()
90+
except:
91+
progress_bar = None
92+
93+
progress_thread = threading.Thread(target=_update_progress)
13694
progress_thread.daemon = True
13795
progress_thread.start()
13896

@@ -147,13 +105,11 @@ def _rotating_progress():
147105
request_completed.set()
148106
progress_thread.join(timeout=1.0)
149107

150-
try:
151-
with progress_lock:
152-
if hasattr(sys.stderr, 'isatty') and sys.stderr.isatty():
153-
sys.stderr.write("\r" + " " * 120 + "\r")
154-
sys.stderr.flush()
155-
except:
156-
pass
108+
if progress_bar:
109+
try:
110+
progress_bar.end()
111+
except:
112+
pass
157113

158114
return response
159115

@@ -162,13 +118,11 @@ def _rotating_progress():
162118
if 'progress_thread' in locals():
163119
progress_thread.join(timeout=1.0)
164120

165-
try:
166-
with progress_lock:
167-
if hasattr(sys.stderr, 'isatty') and sys.stderr.isatty():
168-
sys.stderr.write("\r" + " " * 120 + "\r")
169-
sys.stderr.flush()
170-
except:
171-
pass
121+
if progress_bar:
122+
try:
123+
progress_bar.stop()
124+
except:
125+
pass
172126

173127
raise CLIError(f"Failed to connect to the what-if service: {ex}")
174128

0 commit comments

Comments
 (0)