Skip to content
This repository has been archived by the owner on Nov 15, 2021. It is now read-only.

[refactor-prompt] restore theming support #788

Merged
merged 2 commits into from
Jan 5, 2019
Merged

[refactor-prompt] restore theming support #788

merged 2 commits into from
Jan 5, 2019

Conversation

ixje
Copy link
Member

@ixje ixje commented Jan 4, 2019

What current issue(s) does this address, or what feature is it adding?
resolve the following todo of #623

after the previous item, make sure console themes still work. This requires "Format Tokens" from the prompt_toolkit package, but it should only be applied when used in the CLI. Meaning; the business logic should not be coupled to a PromptInterface() instance because that's the one who creates the theme tokens. solution idea: supply print function as param.

How did you solve this problem?
replace built-in print with prompt_print in the classes below Commands as follows:

from neo.Prompt.PromptPrinter import prompt_print as print

This was the most straight forward way to replace all print calls in command code. One advantage is that we can easily swap out the print call for something custom. One place we do this is for testing where we swap out the prompt_toolkit.print_formatted_text with the buildint print such that all our patch('sys.stdout') in test-cases still work.

In the old prompt some part of the command execution would be themed (e.g. red coloured) whereas others not because they used regular prints. Now everything related to a command response is printed themed.

How did you make sure your solution works?
make test and some manual testing

Are there any special changes in the code that we should be aware of?
see the "how solved" section.

Please check the following, if applicable:

  • Did you add any tests?
  • Did you run make lint?
  • Did you run make test?
  • Are you making a PR to a feature branch or development rather than master?
  • Did you add an entry to CHANGELOG.rst? (if not, please do)

@ixje ixje changed the title [refactor-prompt] re-store theming support [refactor-prompt] restore theming support Jan 4, 2019
Copy link
Contributor

@jseagrave21 jseagrave21 left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

One minor grammatical suggestion. Otherwise, my only question is where is the token_style "number" used? In the original implementation, "number" was used perhaps the most frequently, just for one example see

tokens = [("class:number", out)]
print_formatted_text(FormattedText(tokens), style=self.token_style)
from show_state which is similar to most of the show commands. Am I missing where, the output of the show commands is now in "number" format?

For example,
I don't think the output from show state should look how it currently does because of the default command text formatting:
image

@@ -25,6 +36,9 @@ def test_config(self):
self.assertFalse(res)

def test_config_output(self):
# importing because it setups `peewee` logging, which is checked at the test below
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should be "sets up" not "setups"

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

👍
I was mentally pretty tired at this point. It seems to always show first in language mistakes that I should know 😓 .

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey no worries! I only wish I could be of more help. It seems like you made a big push the other day!

Copy link
Contributor

@jseagrave21 jseagrave21 left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

As a separate feedback, while playing with this new branch I found this error appears when trying to show help for a command with no params such as show state help:

neo> show state help

Show the status of the node

Usage: show state

Could not execute command: max() arg is an empty sequence
  File "/usr/lib/python3.7/threading.py", line 885, in _bootstrap
    self._bootstrap_inner()/2038
  File "/usr/lib/python3.7/threading.py", line 917, in _bootstrap_inner
    self.run()
  File "/usr/lib/python3.7/threading.py", line 865, in run
    self._target(*self._args, **self._kwargs)
  File "/mnt/c/users/jseag/neo/neo-python-ixje/venv/lib/python3.7/site-packages/twisted/_threads/_threadworker.py", line 46, in work
    task()
  File "/mnt/c/users/jseag/neo/neo-python-ixje/venv/lib/python3.7/site-packages/twisted/_threads/_team.py", line 190, in doWork
    task()
  File "/mnt/c/users/jseag/neo/neo-python-ixje/venv/lib/python3.7/site-packages/twisted/python/threadpool.py", line 250, in inContext
    result = inContext.theWork()
  File "/mnt/c/users/jseag/neo/neo-python-ixje/venv/lib/python3.7/site-packages/twisted/python/threadpool.py", line 266, in <lambda>
    inContext.theWork = lambda: context.call(ctx, func, *args, **kw)
  File "/mnt/c/users/jseag/neo/neo-python-ixje/venv/lib/python3.7/site-packages/twisted/python/context.py", line 122, in callWithContext
    return self.currentContext().callWithContext(ctx, func, *args, **kw)
  File "/mnt/c/users/jseag/neo/neo-python-ixje/venv/lib/python3.7/site-packages/twisted/python/context.py", line 85, in callWithContext
    return func(*args,**kw)
  File "/mnt/c/users/jseag/neo/neo-python-ixje/neo/bin/prompt.py", line 216, in run
    traceback.print_stack()
Traceback (most recent call last):
  File "/mnt/c/users/jseag/neo/neo-python-ixje/neo/bin/prompt.py", line 200, in run
    cmd.handle_help(arguments)
  File "/mnt/c/users/jseag/neo/neo-python-ixje/neo/Prompt/CommandBase.py", line 147, in handle_help
    self.__sub_commands[item].handle_help(arguments[1:])
  File "/mnt/c/users/jseag/neo/neo-python-ixje/neo/Prompt/CommandBase.py", line 143, in handle_help
    self.__print_absolute_cmd_help()
  File "/mnt/c/users/jseag/neo/neo-python-ixje/neo/Prompt/CommandBase.py", line 117, in __print_absolute_cmd_help
    longest_param_name = max(min_indent, max(len(p.name) for p in self.command_desc().params))
ValueError: max() arg is an empty sequence

so, I recommend this change in CommandBase.py:

replace

def __print_absolute_cmd_help(self):
        print(f"\n{self.command_desc().short_help.capitalize()}")
        params = ""
        for p in self.command_desc().params:
            params += f"{p.formatted_name()} "
        print(f"\nUsage: {self.__command_with_parents()} {params}\n")

        min_indent = 15
        longest_param_name = max(min_indent, max(len(p.name) for p in self.command_desc().params))
        for p in self.command_desc().params:
            print(p.to_str(longest_param_name))

with:

def __print_absolute_cmd_help(self):
        print(f"\n{self.command_desc().short_help.capitalize()}")
        params = ""
        for p in self.command_desc().params:
            params += f"{p.formatted_name()} "
        print(f"\nUsage: {self.__command_with_parents()} {params}\n")

        min_indent = 15
        try:
            longest_param_name = max(min_indent, max(len(p.name) for p in self.command_desc().params))
            for p in self.command_desc().params:
                print(p.to_str(longest_param_name))
        except ValueError:
            pass

this achieves the desired results with minimal changes.

Copy link
Contributor

@jseagrave21 jseagrave21 left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A final separate issue I noticed is that the wallet command does not have an adequate help description. I recommend changing command_desc in CommandWallet to:

def command_desc(self):
        return CommandDesc('wallet', 'show wallet details or manage wallets\n\n'
                           f"{' ':>20} Usage Examples:\n"
                           f"{' ':>23} wallet\n"
                           f"{' ':>23} wallet COMMAND\n")

this change illustrates that wallet is a standalone command (and in my opinion, it is probably the most used command).

@ixje
Copy link
Member Author

ixje commented Jan 5, 2019

I don't think the output from show state should look how it currently does because of the default command text formatting:

What would you have in mind it should look like?

My thoughts on the current approach were;
there are 2 types of information being printed on the console. 1) information triggered by us and information triggered in the background by networking code, VM execution etc. The former could be limited to cli command responses and are (currently) in red, the latter are in whatever colour the logger (debug,info,error) prints them. This gives a clear distinction for the user what they caused and what not.

I know it's a bit limited in the presentation, but I think that can be handled/improved with #624

@ixje
Copy link
Member Author

ixje commented Jan 5, 2019

A final separate issue I noticed is that the wallet command does not have an adequate help description. I recommend changing command_desc in CommandWallet to:

we can't do that because that will give

neo> help

Commands:
   config          - configure internal settings
   sc              - develop smart contracts
   search          - search the blockchain
   show            - show various node and blockchain data
   wallet          - show wallet details or manage wallets

                     Usage Examples:
                        wallet
                        wallet COMMAND

if we ever get a base group command with e.g. a z then you'd get something

neo> help

Commands:
   config          - configure internal settings
   sc              - develop smart contracts
   search          - search the blockchain
   show            - show various node and blockchain data
   wallet          - show wallet details or manage wallets

                     Usage Examples:
                        wallet
                        wallet COMMAND
    z-group        - my custom command

Not too pretty imo. The best I can come up with is

neo> wallet help

Usage: wallet COMMAND (or "wallet" to show the wallet contents)

This requires changing all double underscore methods/attributes in CommandBase to single underscore such that we can override handle_help() for CommandWallet. I'll ping Lysander on slack to see if he has ideas (can't tag him here)

@ixje
Copy link
Member Author

ixje commented Jan 5, 2019

addressed the show state help issue in a separate PR #792

@LysanderGG
Copy link
Contributor

Reply to #788 (comment)

I can think of a few solutions:

  1. have one (or several) subfunctions returning a string that handle_help would print, instead of directly printing.
    For this particular case, we could have:
def _usage_str(self):
    return f"Usage: {self.__command_with_parents()} COMMAND"

def handle_help(self, arguments):
        item = get_arg(arguments)
        if item == 'help':
            if len(self.__sub_commands) > 0:
                # show overview of subcommands and their purpose
                print(f"\n{self._usage_str()}\n")
                print(f"{self.command_desc().short_help.capitalize()}\n")
                ...

Then overriding _usage_str for CommandWallet should handle this problem.

  1. We could restore the original idea of having a short help message and a longer help message.
    If the long help message is not defined, it would be the same as the short one.

The longer help could be used outside of listings.
For this particular problem, we would only need to provide a long help for CommandWallet.

  1. Almost same as 2. but instead of adding a member to CommandDesc, we could define the following command that could be overwritten:
def longer_help(self):
    return self.command_desc().short_help

I don't think one is better than another for now 🤔
Maybe 1. is good enough for now and simple enough.

@jseagrave21
Copy link
Contributor

What would you have in mind it should look like?

I was just referring back to the original presentation, where most outputs were in "number" format. In this case, I think the thinking was there were three types instead of two: input, ouput, and other. So all commands, seen when using help, would be red since they are commmands, but all outputs would be in "number" format, except for unrequested outputs like you mentioned (e.g. errors, etc.) .

I know it's a bit limited in the presentation, but I think that can be handled/improved with #624

Maybe it is better to table this discussion til then?

@ixje ixje merged commit e4540d4 into CityOfZion:refactor-prompt Jan 5, 2019
@ixje ixje deleted the restore-theming branch January 5, 2019 14:46
jseagrave21 pushed a commit to jseagrave21/neo-python that referenced this pull request Jan 7, 2019
* re-store theming support

* fix comment
ixje added a commit that referenced this pull request Jan 8, 2019
…ython into refactor-prompt

* 'refactor-prompt' of https://github.com/CityOfZion/neo-python: (37 commits)
  fix calculation of change value when using alternating asset inputs (#803)
  [refactor-prompt] Fix #800 (#802)
  [refactor-prompt] Improve send & sendmany (third try) (#799)
  Fix send/sendmany default wallet source address for tx (#796)
  fix prompt printer for lists and other possible objects (#795)
  clarify insufficient funds error message due to not enough unspent outputs (#793)
  improve wallet usage help (#794)
  [refactor-prompt] restore theming support (#788)
  [refactor-prompt] update docs (#789)
  [refactor-prompt] enforce pw prompt send (#791)
  fix exception in help if command has no params (#792)
  add wallet password checking before exporting (#790)
  streamline parameter descriptions (#787)
  [refactor-prompt] add sc invoke (#786)
  [refactor-prompt] add sc deploy (#785)
  [refactor-prompt] add debugstorage command (#784)
  [refactor-prompt] cleanup 2 (#783)
  [refactor-prompt] add support for the sc group including build, build_run, and load_run (#779)
  split prompt wallet into multiple files (#782)
  Add wallet import contract_addr (#777)
  ...
ixje added a commit that referenced this pull request Jan 10, 2019
* Add the bases for making prompt commands plugin based (#720)

* WIP make prompt commands plugin based

Signed-off-by: Guillaume George <[email protected]>

* Merge ixje:refactor-prompt

Signed-off-by: Guillaume George <[email protected]>

* Handle help detection in prompt.py

Signed-off-by: Guillaume George <[email protected]>

* Use CommandBase for subcommands to be able to have N levels of commands.

Signed-off-by: Guillaume George <[email protected]>

* Move "create wallet" command into "wallet"

Signed-off-by: Guillaume George <[email protected]>

* Improve CommandBase.register_sub_command to use the subcommand's CommandDesc.command as an id. (#725)

Signed-off-by: Guillaume George <[email protected]>

* Fix 1 word commands (#727)

* Improve CommandBase.register_sub_command to use the subcommand's CommandDesc.command as an id.

Signed-off-by: Guillaume George <[email protected]>

* Fix exception when a command was used without arguments (for example "wallet")

Signed-off-by: Guillaume George <[email protected]>

* Add support for `wallet` `send`, `sendmany`, `sign`, `open`, and `close` (#726)

* Prompt cleanup (#730)

* Update description and clarify debug logs

* Make return's explicit, clarify multi-sig help message

* cleanup prompt

* remove colour from initial help, sort commands alphabetically, cleanup descriptions

* fix linting

* process feedback

* [refactor-prompt] Prompt fixes (#732)

* Improve CommandBase.register_sub_command to use the subcommand's CommandDesc.command as an id.

Signed-off-by: Guillaume George <[email protected]>

* Fix CommandWalletCreateAddress missing parameter desc

Signed-off-by: Guillaume George <[email protected]>

* Fix missing words for autocompletion

Signed-off-by: Guillaume George <[email protected]>

* [refactor-prompt] Add missing tests for wallet create, verbose and create_addr (#733)

* Add missing tests for wallet create, verbose and create_addr

Signed-off-by: Guillaume George <[email protected]>

* fix reviews

Signed-off-by: Guillaume George <[email protected]>

* [refactor prompt] Add support for search method group (#739)

* [refactor prompt] Add support for show method group (pt 1) (#738)

* Fix NodeLeader was not reset between test cases. (#742)

This would lead to some problems when the blockchain is reset but the NodeLeader instance members are not.
Transactions were still considered as known.

Some members were not reset in NodeLeader.Setup()
Also removed unsued member NodeLeader.MissionsGlobal

Signed-off-by: Guillaume George <[email protected]>

* Migrate command: wallet rebuild (#747)

Signed-off-by: Guillaume George <[email protected]>

* remove deprecated migrate command

* remove deprecated migrate command (#748)

* [refactor prompt] Add support for show method group (pt 2) (#741)

* [refactor-prompt] Implement CommandWalletClaimGas (#740)

* [refactor-prompt] Add wallet token base + delete (#757)

* [refactor-prompt] Migrate command: wallet delete_addr (#752)

* Migrate command: wallet delete_addr

Signed-off-by: Guillaume George <[email protected]>

* UserWallet.DeleteAddress now returns False on error + proper handling of invalid addresses in CommandWalletDeleteAddress

Signed-off-by: Guillaume George <[email protected]>

* Migrate command: wallet alias (#753)

Signed-off-by: Guillaume George <[email protected]>

* [refactor-prompt] Add wallet token send (#758)

* remove deprecated migrate command

* Add wallet token send

* Update requirements and use isValidPublicAddress from new neo-python-core version

* - fix send token description
- process feedback

* fix doc string typo

* [refactor prompt] Add support for config group pt1 (#759)

* add wallet import nep2/wif (#765)

* [refactor-prompt] add wallet token history (#763)

* Add wallet token history

* process feedback

* fix broken test after base branch merge

* [refactor-prompt] add wallet export commands (#764)

* add wallet export commands

* Fix export nep2 to ask for passwords to prevent pw leaking to logs

* process feedback

* [refactor-prompt] add wallet import watchaddr (#766)

* [refactor-prompt] add token sendfrom (#761)

* [refactor-prompt] add import multisig_addr (#767)

* add import multsig address

* remove obsolete function

* [refactor-prompt] Migrate command: wallet unspent (#760)

* migrate command: wallet unspent

Signed-off-by: Guillaume George <[email protected]>

* wallet unspent - add tests

Signed-off-by: Guillaume George <[email protected]>

* fix arguments names and missing doc

Signed-off-by: Guillaume George <[email protected]>

* Handle review: add feedback when there is no asset matching the arguments + use neocore.Utils.isValidPublicAddress

Signed-off-by: Guillaume George <[email protected]>

* [refactor prompt] Add support for config maxpeers (#762)

* add token approve and token allowance (#769)

* add config nep8 (#771)

* [refactor-prompt] Migrate command: wallet split (#770)

* Migrate command wallet split

Signed-off-by: Guillaume George <[email protected]>

* Fix some comments

Signed-off-by: Guillaume George <[email protected]>

* Fix command desc + remove print() calls committed by mistake

Signed-off-by: Guillaume George <[email protected]>

* Add tests for CommandWalletSplit

Signed-off-by: Guillaume George <[email protected]>

* Review: test_wallet_split use string arguments instead of ints

Signed-off-by: Guillaume George <[email protected]>

* Handle Reviews - handle negative fees, improve error messages

Signed-off-by: Guillaume George <[email protected]>

* add token mint (#773)

* [refactor prompt] Fix `search asset` and `search contract` (#774)

* Update prompt.py

- add CommandShow and CommandSearch to prompt

* Update prompt.py

revert changes

* Update Search.py

- update `search contract` and `search asset` per #623 (comment)

* Update test_search_commands.py

- add tests in case no search parameter is provided

* add token register (#775)

* [refactor-prompt] Migrate command: wallet import token (#772)

* test_wallet_commands.py: Move tests of non commands at the end

Signed-off-by: Guillaume George <[email protected]>

* Add wallet import token

Signed-off-by: Guillaume George <[email protected]>

* Review: return None implicitly where possible

Signed-off-by: Guillaume George <[email protected]>

* Add a few tests for SplitUnspentCoin()

Signed-off-by: Guillaume George <[email protected]>

* CommandWalletImportToken - Handle review: better validation of contract_hash

Signed-off-by: Guillaume George <[email protected]>

* Add wallet import contract_addr (#777)

Signed-off-by: Guillaume George <[email protected]>

* split prompt wallet into multiple files (#782)

* [refactor-prompt] add support for the sc group including build, build_run, and load_run (#779)

* [refactor-prompt] cleanup 2 (#783)

* make base command response consistent

* fix plurality

* check input parameters before closing wallet

* streamline missing arguments response
streamline accepted boolean options for config

* process feedback

* [refactor-prompt] add debugstorage command (#784)

* add debugstorage command (and fix auto save linting error)

* correct comments

* [refactor-prompt] add sc deploy (#785)

* add sc deploy (previously known as; import contract)

* process feedback

* [refactor-prompt] add sc invoke (#786)

* add sc invoke (previously known as testinvoke)

* process feedback

* streamline parameter descriptions (#787)

* add wallet password checking before exporting (#790)

* fix exception in help if command has no params (#792)

* [refactor-prompt] enforce pw prompt send (#791)

* remove password bypass

* remove unused import

* [refactor-prompt] update docs (#789)

* update global readme

* update docs

* process feedback

* update show contract output

* [refactor-prompt] restore theming support (#788)

* re-store theming support

* fix comment

* improve wallet usage help (#794)

* clarify insufficient funds error message due to not enough unspent outputs (#793)

* fix prompt printer for lists and other possible objects (#795)

* Fix send/sendmany default wallet source address for tx (#796)

* [refactor-prompt] Improve send & sendmany (third try) (#799)

* Update Send.py

* Update test_send_command.py

* rename test_send_command.py as test_send_commands.py

* [refactor-prompt] Fix #800 (#802)

* Update prompt.py

- add CommandShow and CommandSearch to prompt

* Update prompt.py

revert changes

* Fix #800

- adds support for contracts not requiring params

* fix calculation of change value when using alternating asset inputs (#803)

* test print fix

* oops

* test again

* update makefile

* update changelog to trigger stuck build
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants