Skip to content

Commit

Permalink
Have help printing pay attention to --colors
Browse files Browse the repository at this point in the history
  • Loading branch information
gshuflin committed Jul 14, 2020
1 parent 568329f commit b95b144
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 39 deletions.
3 changes: 2 additions & 1 deletion src/python/pants/bin/local_pants_runner.py
Expand Up @@ -275,9 +275,10 @@ def run(self, start_time: float) -> ExitCode:
self.graph_session.goal_consumed_subsystem_scopes,
)
help_printer = HelpPrinter(
bin_name=self.options.for_global_scope().pants_bin_name,
bin_name=global_options.pants_bin_name,
help_request=self.options.help_request,
all_help_info=all_help_info,
use_color=global_options.colors,
)
return help_printer.print_help()

Expand Down
68 changes: 33 additions & 35 deletions src/python/pants/help/help_printer.py
@@ -1,8 +1,8 @@
# Copyright 2015 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).

import sys
import textwrap
from dataclasses import dataclass
from typing import Dict, cast

from colors import cyan, green
Expand All @@ -22,35 +22,33 @@
from pants.option.scope import GLOBAL_SCOPE


@dataclass(frozen=True)
class HelpPrinter:
"""Prints help to the console."""

def __init__(
self, *, bin_name: str, help_request: HelpRequest, all_help_info: AllHelpInfo
) -> None:
self._bin_name = bin_name
self._help_request = help_request
self._all_help_info = all_help_info
self._use_color = sys.stdout.isatty()
bin_name: str
help_request: HelpRequest
all_help_info: AllHelpInfo
use_color: bool

def print_help(self) -> Literal[0, 1]:
"""Print help to the console."""

def print_hint() -> None:
print(f"Use `{self._bin_name} goals` to list goals.")
print(f"Use `{self._bin_name} help` to get help.")
print(f"Use `{self.bin_name} goals` to list goals.")
print(f"Use `{self.bin_name} help` to get help.")

if isinstance(self._help_request, VersionHelp):
if isinstance(self.help_request, VersionHelp):
print(pants_version())
elif isinstance(self._help_request, OptionsHelp):
elif isinstance(self.help_request, OptionsHelp):
self._print_options_help()
elif isinstance(self._help_request, GoalsHelp):
elif isinstance(self.help_request, GoalsHelp):
self._print_goals_help()
elif isinstance(self._help_request, UnknownGoalHelp):
print("Unknown goals: {}".format(", ".join(self._help_request.unknown_goals)))
elif isinstance(self.help_request, UnknownGoalHelp):
print("Unknown goals: {}".format(", ".join(self.help_request.unknown_goals)))
print_hint()
return 1
elif isinstance(self._help_request, NoGoalHelp):
elif isinstance(self.help_request, NoGoalHelp):
print("No goals specified.")
print_hint()
return 1
Expand All @@ -59,21 +57,21 @@ def print_hint() -> None:
def _print_goals_help(self) -> None:
goal_descriptions: Dict[str, str] = {}

for goal_info in self._all_help_info.name_to_goal_info.values():
for goal_info in self.all_help_info.name_to_goal_info.values():
if goal_info.is_implemented:
goal_descriptions[goal_info.name] = goal_info.description

title_text = "Goals"
title = f"{title_text}\n{'-' * len(title_text)}"
if self._use_color:
if self.use_color:
title = green(title)

max_width = max((len(name) for name in goal_descriptions.keys()), default=0)
chars_before_description = max_width + 2

def format_goal(name: str, descr: str) -> str:
name = name.ljust(chars_before_description)
if self._use_color:
if self.use_color:
name = cyan(name)
description_lines = textwrap.wrap(descr, 80 - chars_before_description)
if len(description_lines) > 1:
Expand All @@ -86,7 +84,7 @@ def format_goal(name: str, descr: str) -> str:

lines = [
f"\n{title}\n",
f"Use `{self._bin_name} help $goal` to get help for a particular goal.",
f"Use `{self.bin_name} help $goal` to get help for a particular goal.",
"\n",
*(
format_goal(name, description)
Expand All @@ -98,15 +96,15 @@ def format_goal(name: str, descr: str) -> str:
def _print_options_help(self) -> None:
"""Print a help screen.
Assumes that self._help_request is an instance of OptionsHelp.
Assumes that self.help_request is an instance of OptionsHelp.
Note: Ony useful if called after options have been registered.
"""

help_request = cast(OptionsHelp, self._help_request)
help_request = cast(OptionsHelp, self.help_request)

if help_request.all_scopes:
help_scopes = set(self._all_help_info.scope_to_help_info.keys())
help_scopes = set(self.all_help_info.scope_to_help_info.keys())
else:
# The scopes explicitly mentioned by the user on the cmd line.
help_scopes = set(help_request.scopes)
Expand All @@ -124,23 +122,23 @@ def _print_global_help(self, advanced: bool):
print(pants_release())
print("\nUsage:")
print(
f" {self._bin_name} [option ...] [goal ...] [target/file ...] Attempt the specified goals."
f" {self.bin_name} [option ...] [goal ...] [target/file ...] Attempt the specified goals."
)
print(f" {self._bin_name} help Get help.")
print(f" {self.bin_name} help Get help.")
print(
f" {self._bin_name} help [goal/subsystem] Get help for a goal or subsystem."
f" {self.bin_name} help [goal/subsystem] Get help for a goal or subsystem."
)
print(
f" {self._bin_name} help-advanced Get help for global advanced options."
f" {self.bin_name} help-advanced Get help for global advanced options."
)
print(
f" {self._bin_name} help-advanced [goal/subsystem] Get help for a goal's or subsystem's advanced options."
f" {self.bin_name} help-advanced [goal/subsystem] Get help for a goal's or subsystem's advanced options."
)
print(
f" {self._bin_name} help-all Get help for all goals and subsystems."
f" {self.bin_name} help-all Get help for all goals and subsystems."
)
print(
f" {self._bin_name} goals List all installed goals."
f" {self.bin_name} goals List all installed goals."
)
print("")
print(" [file] can be:")
Expand All @@ -156,23 +154,23 @@ def _print_global_help(self, advanced: bool):
def _format_help(self, scope: str, show_advanced_and_deprecated: bool) -> str:
"""Return a help message for the options registered on this object.
Assumes that self._help_request is an instance of OptionsHelp.
Assumes that self.help_request is an instance of OptionsHelp.
"""
help_formatter = HelpFormatter(
show_advanced=show_advanced_and_deprecated,
show_deprecated=show_advanced_and_deprecated,
color=self._use_color,
color=self.use_color,
)
oshi = self._all_help_info.scope_to_help_info.get(scope)
oshi = self.all_help_info.scope_to_help_info.get(scope)
if not oshi:
return ""
formatted_lines = help_formatter.format_options(oshi)
goal_info = self._all_help_info.name_to_goal_info.get(scope)
goal_info = self.all_help_info.name_to_goal_info.get(scope)
if goal_info:
related_scopes = sorted(set(goal_info.consumed_scopes) - {GLOBAL_SCOPE})
if related_scopes:
related_subsystems_label = "Related subsystems:"
if self._use_color:
if self.use_color:
related_subsystems_label = green(related_subsystems_label)
formatted_lines.append(f"{related_subsystems_label} {', '.join(related_scopes)}")
formatted_lines.append("")
Expand Down
6 changes: 3 additions & 3 deletions src/rust/engine/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

0 comments on commit b95b144

Please sign in to comment.