Skip to content

Commit

Permalink
Merge pull request #152 from HyperLink-Technology/v1.0.0b9
Browse files Browse the repository at this point in the history
V1.0.0b9
  • Loading branch information
iamdefinitelyahuman authored Jul 3, 2019
2 parents 37c4149 + adb7b63 commit 6dc29de
Show file tree
Hide file tree
Showing 41 changed files with 656 additions and 313 deletions.
7 changes: 7 additions & 0 deletions CHANGELOG
Original file line number Diff line number Diff line change
@@ -1,3 +1,10 @@
1.0.0b9
-------

- Support for overloaded function names
- Bugfixes
- Minor code changes and improvements

1.0.0b8
-------

Expand Down
11 changes: 6 additions & 5 deletions brownie/_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,8 @@

def _load_default_config():
'''Loads the default configuration settings from brownie/data/config.json'''
path = Path(__file__).parent.joinpath("data/config.json")
config = _Singleton("Config", (StrictDict,), {})(json.load(path.open()))
with Path(__file__).parent.joinpath("data/config.json").open() as f:
config = _Singleton("Config", (StrictDict,), {})(json.load(f))
config['folders'] = {
'brownie': str(Path(__file__).parent),
'project': None
Expand All @@ -44,9 +44,10 @@ def load_project_config(project_path):
CONFIG._unlock()
CONFIG['folders']['project'] = str(project_path)
config_path = project_path.joinpath("brownie-config.json")
if config_path.exists():
_recursive_update(CONFIG, json.load(config_path.open()), [])
else:
try:
with config_path.open() as f:
_recursive_update(CONFIG, json.load(f), [])
except FileNotFoundError:
shutil.copy(
str(Path(CONFIG['folders']['brownie']).joinpath("data/config.json")),
str(config_path)
Expand Down
2 changes: 1 addition & 1 deletion brownie/cli/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
from brownie.exceptions import ProjectNotFound
from brownie._config import ARGV

__version__ = "1.0.0b8" # did you change this in docs/conf.py as well?
__version__ = "1.0.0b9" # did you change this in docs/conf.py as well?

__doc__ = """Usage: brownie <command> [<args>...] [options <args>]
Expand Down
9 changes: 1 addition & 8 deletions brownie/cli/console.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,8 @@
#!/usr/bin/python3

from docopt import docopt
from pathlib import Path

import brownie
from brownie import network, project
from brownie.test.main import run_script
from brownie.cli.utils.console import Console
from brownie._config import ARGV, CONFIG

Expand All @@ -29,9 +26,5 @@ def main():
project.load()
network.connect(ARGV['network'])

console_dict = dict((i, getattr(brownie, i)) for i in brownie.__all__)
console_dict['run'] = run_script
del console_dict['project']

shell = Console(console_dict, Path(CONFIG['folders']['project']).joinpath('.history'))
shell = Console()
shell.interact(banner="Brownie environment is ready.", exitmsg="")
12 changes: 12 additions & 0 deletions brownie/cli/utils/color.py
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,8 @@ def _write(self, value):
return f"{s}{self[key]}{value}{self['dull']}{s}"

def format_tb(self, exc, filename=None, start=None, stop=None):
if exc[0] is SyntaxError:
return self.format_syntaxerror(exc[1])
tb = [i.replace("./", "") for i in traceback.format_tb(exc[2])]
if filename and not ARGV['tb']:
try:
Expand All @@ -134,6 +136,16 @@ def format_tb(self, exc, filename=None, start=None, stop=None):
tb.append(f"{self['error']}{exc[0].__name__}{self}: {exc[1]}")
return "\n".join(tb)

def format_syntaxerror(self, exc):
offset = exc.offset+len(exc.text.lstrip())-len(exc.text)+3
if CONFIG['folders']['project']:
exc.filename = exc.filename.replace(CONFIG['folders']['project'], ".")
return (
f" {self['dull']}File \"{self['string']}{exc.filename}{self['dull']}\", line "
f"{self['value']}{exc.lineno}{self['dull']},\n{self} {exc.text.strip()}\n"
f"{' '*offset}^\n{self['error']}SyntaxError{self}: {exc.msg}"
)


def notify(type_, msg):
'''Prepends a message with a colored tag and outputs it to the console.'''
Expand Down
37 changes: 26 additions & 11 deletions brownie/cli/utils/console.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,15 @@
#!/usr/bin/python3

import atexit
import builtins
import code
from pathlib import Path
import sys

import brownie
from brownie.test.main import run_script
from . import color
from brownie._config import CONFIG

if sys.platform == "win32":
from pyreadline import Readline
Expand All @@ -16,15 +20,21 @@

class Console(code.InteractiveConsole):

def __init__(self, locals_dict, history_file):
def __init__(self):
locals_dict = dict((i, getattr(brownie, i)) for i in brownie.__all__)
locals_dict['run'] = run_script
del locals_dict['project']

builtins.dir = self._dir
self._stdout_write = sys.stdout.write
sys.stdout.write = self._console_write
history_file = Path(history_file)
if not history_file.exists():
history_file.open('w').write("")
self._readline = str(history_file)
readline.read_history_file(self._readline)

history_file = str(Path(CONFIG['folders']['project']).joinpath('.history').absolute())
atexit.register(_atexit_readline, history_file)
try:
readline.read_history_file(history_file)
except (FileNotFoundError, OSError):
pass
super().__init__(locals_dict)

# replaces builtin dir method, for simplified and colorful output
Expand All @@ -49,6 +59,10 @@ def _console_write(self, text):
pass
return self._stdout_write(text)

def showsyntaxerror(self, filename):
tb = color.format_syntaxerror(sys.exc_info()[1])
self.write(tb+'\n')

def showtraceback(self):
tb = color.format_tb(sys.exc_info(), start=1)
self.write(tb+'\n')
Expand All @@ -63,12 +77,8 @@ def push(self, line):
readline.get_current_history_length() - 1,
line[:line.index("(")] + "()"
)
except (ValueError, AttributeError):
except (ValueError, AttributeError, KeyError):
pass
if sys.platform == "win32":
readline.write_history_file(self._readline)
else:
readline.append_history_file(1, self._readline)
return super().push(line)


Expand All @@ -80,3 +90,8 @@ def _dir_color(obj):
if not callable(obj):
return color('value')
return color('callable')


def _atexit_readline(history_file):
readline.set_history_length(1000)
readline.write_history_file(history_file)
4 changes: 0 additions & 4 deletions brownie/exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,6 @@ class UnknownAccount(Exception):
pass


class AmbiguousMethods(Exception):
pass


class UndeployedLibrary(Exception):
pass

Expand Down
3 changes: 2 additions & 1 deletion brownie/gui/select.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,8 @@ def __init__(self, parent, report_paths):
self._reports = {}
for path in report_paths:
try:
self._reports[path.stem] = json.load(path.open())
with path.open() as f:
self._reports[path.stem] = json.load(f)
except Exception:
continue
super().__init__(
Expand Down
3 changes: 2 additions & 1 deletion brownie/gui/textbook.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,8 @@ def add(self, path):
label = path.name
if label in [i._label for i in self._frames]:
return
frame = TextBox(self, path.open().read())
with path.open() as f:
frame = TextBox(self, f.read())
super().add(frame, text=" {} ".format(label))
frame._id = len(self._frames)
frame._label = label
Expand Down
27 changes: 15 additions & 12 deletions brownie/network/account.py
Original file line number Diff line number Diff line change
Expand Up @@ -101,11 +101,12 @@ def load(self, filename=None):
if not json_file.exists():
json_file = project_path.joinpath(filename)
if not json_file.exists():
raise FileNotFoundError("Cannot find {}".format(json_file))
priv_key = web3.eth.account.decrypt(
json.load(json_file.open()),
getpass("Enter the password for this account: ")
)
raise FileNotFoundError(f"Cannot find {json_file}")
with json_file.open() as f:
priv_key = web3.eth.account.decrypt(
json.load(f),
getpass("Enter the password for this account: ")
)
return self.add(priv_key)

def at(self, address):
Expand All @@ -122,7 +123,7 @@ def at(self, address):
try:
return next(i for i in self._accounts if i == address)
except StopIteration:
raise UnknownAccount("No account exists for {}".format(address))
raise UnknownAccount(f"No account exists for {address}")

def remove(self, address):
'''Removes an account instance from the container.
Expand All @@ -133,7 +134,7 @@ def remove(self, address):
try:
self._accounts.remove(address)
except ValueError:
raise UnknownAccount("No account exists for {}".format(address))
raise UnknownAccount(f"No account exists for {address}")

def clear(self):
'''Empties the container.'''
Expand All @@ -152,7 +153,7 @@ def __hash__(self):
return hash(self.address)

def __repr__(self):
return "'{0[string]}{1}{0}'".format(color, self.address)
return f"'{color['string']}{self.address}{color}'"

def __str__(self):
return self.address
Expand Down Expand Up @@ -290,7 +291,7 @@ class Account(_AccountBase):
nonce: Current nonce of the account.'''

def __repr__(self):
return "<Account object '{0[string]}{1}{0}'>".format(color, self.address)
return f"<Account object '{color['string']}{self.address}{color}'>"

def _transact(self, tx):
self._check_for_revert(tx)
Expand All @@ -314,7 +315,7 @@ def __init__(self, address, account, priv_key):
super().__init__(address)

def __repr__(self):
return "<LocalAccount object '{0[string]}{1}{0}'>".format(color, self.address)
return f"<LocalAccount object '{color['string']}{self.address}{color}'>"

def save(self, filename, overwrite=False):
'''Encrypts the private key and saves it in a keystore json.
Expand All @@ -341,7 +342,8 @@ def save(self, filename, overwrite=False):
self.private_key,
getpass("Enter the password to encrypt this account with: ")
)
json.dump(encrypted, json_file.open('w'))
with json_file.open('w') as f:
json.dump(encrypted, f)
return str(json_file)

def _transact(self, tx):
Expand All @@ -356,7 +358,8 @@ def _raise_or_return_tx(exc):
txid = next(i for i in data.keys() if i[:2] == "0x")
reason = data[txid]['reason'] if 'reason' in data[txid] else None
pc = data[txid]['program_counter'] - 1
return txid, (reason, pc)
error = data[txid]['error']
return txid, [reason, pc, error]
except SyntaxError:
raise exc
except Exception:
Expand Down
5 changes: 3 additions & 2 deletions brownie/network/alert.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ def __init__(self, fn, args=[], kwargs={}, delay=0.5, msg=None, callback=None):
target=self._loop, daemon=True,
args=(fn, args, kwargs, delay, msg, callback))
self._thread.start()
self.start_time = time.time()
_instances.add(self)

def _loop(self, fn, args, kwargs, delay, msg, callback):
Expand All @@ -50,7 +51,7 @@ def _loop(self, fn, args, kwargs, delay, msg, callback):
continue
if msg:
msg = msg.format(start_value, value)
print("{0[bright red]}ALERT{0}: {1}".format(color, msg))
print(f"{color['bright red']}ALERT{color}: {msg}")
if callback:
callback(start_value, value)
_instances.discard(self)
Expand All @@ -70,7 +71,7 @@ def new(fn, args=[], kwargs={}, delay=0.5, msg=None, callback=None):

def show():
'''Returns a list of all currently active Alert instances.'''
return list(_instances)
return sorted(_instances, key=lambda k: k.start_time)


def stop_all():
Expand Down
Loading

0 comments on commit 6dc29de

Please sign in to comment.