Skip to content

Commit 350126e

Browse files
authored
Add black to ethpm (#2345)
1 parent a94d5bb commit 350126e

16 files changed

+63
-47
lines changed

ethpm/_utils/backend.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,7 @@
4343

4444
@to_tuple
4545
def get_translatable_backends_for_uri(
46-
uri: URI
46+
uri: URI,
4747
) -> Generator[Type[BaseURIBackend], None, None]:
4848
# type ignored because of conflict with instantiating BaseURIBackend
4949
for backend in ALL_URI_BACKENDS:
@@ -56,7 +56,7 @@ def get_translatable_backends_for_uri(
5656

5757
@to_tuple
5858
def get_resolvable_backends_for_uri(
59-
uri: URI
59+
uri: URI,
6060
) -> Generator[Type[BaseURIBackend], None, None]:
6161
# special case the default IPFS backend to the first slot.
6262
default_ipfs = get_ipfs_backend_class()

ethpm/_utils/cache.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ class cached_property:
1616
def __init__(self, func: Callable[..., Any], name: str = None) -> None:
1717
self.wrapped_func = func
1818
self.name = name
19-
self.__doc__ = getattr(func, '__doc__')
19+
self.__doc__ = getattr(func, "__doc__")
2020

2121
def __get__(self, instance: Any, cls: Any = None) -> Any:
2222
"""

ethpm/_utils/chains.py

+5-1
Original file line numberDiff line numberDiff line change
@@ -57,7 +57,11 @@ def parse_BIP122_uri(blockchain_uri: URI) -> Tuple[HexStr, str, HexStr]:
5757
if match is None:
5858
raise ValueError(f"Invalid URI format: '{blockchain_uri}'")
5959
chain_id, resource_type, resource_hash = match.groups()
60-
return (add_0x_prefix(HexStr(chain_id)), resource_type, add_0x_prefix(HexStr(resource_hash)))
60+
return (
61+
add_0x_prefix(HexStr(chain_id)),
62+
resource_type,
63+
add_0x_prefix(HexStr(resource_hash)),
64+
)
6165

6266

6367
def is_BIP122_block_uri(value: URI) -> bool:

ethpm/backends/registry.py

+9-10
Original file line numberDiff line numberDiff line change
@@ -34,8 +34,7 @@
3434
# TODO: Update registry ABI once ERC is finalized.
3535
REGISTRY_ABI = fetch_standard_registry_abi()
3636
RegistryURI = namedtuple(
37-
"RegistryURI",
38-
["address", "chain_id", "name", "version", "namespaced_asset", "ens"]
37+
"RegistryURI", ["address", "chain_id", "name", "version", "namespaced_asset", "ens"]
3938
)
4039

4140

@@ -48,6 +47,7 @@ class RegistryURIBackend(BaseURIBackend):
4847

4948
def __init__(self) -> None:
5049
from web3.auto.infura import w3
50+
5151
self.w3 = w3
5252

5353
def can_translate_uri(self, uri: str) -> bool:
@@ -61,11 +61,9 @@ def fetch_uri_contents(self, uri: str) -> URI:
6161
Return content-addressed URI stored at registry URI.
6262
"""
6363
address, chain_id, pkg_name, pkg_version, _, _ = parse_registry_uri(uri)
64-
if chain_id != '1':
64+
if chain_id != "1":
6565
# todo: support all testnets
66-
raise CannotHandleURI(
67-
"Currently only mainnet registry uris are supported."
68-
)
66+
raise CannotHandleURI("Currently only mainnet registry uris are supported.")
6967
self.w3.enable_unstable_package_management_api()
7068
self.w3.pm.set_registry(address)
7169
_, _, manifest_uri = self.w3.pm.get_release_data(pkg_name, pkg_version)
@@ -90,6 +88,7 @@ def parse_registry_uri(uri: str) -> RegistryURI:
9088
Validate and return (authority, chain_id, pkg_name, version) from a valid registry URI.
9189
"""
9290
from web3.auto.infura import w3
91+
9392
validate_registry_uri(uri)
9493
parsed_uri = parse.urlparse(uri)
9594
if ":" in parsed_uri.netloc:
@@ -104,14 +103,14 @@ def parse_registry_uri(uri: str) -> RegistryURI:
104103
address = ns.address(address_or_ens)
105104
ens = address_or_ens
106105
else:
107-
raise CannotHandleURI(
108-
f"Invalid address or ENS domain found in uri: {uri}."
109-
)
106+
raise CannotHandleURI(f"Invalid address or ENS domain found in uri: {uri}.")
110107
pkg_name, pkg_version, namespaced_asset = _process_pkg_path(parsed_uri.path)
111108
return RegistryURI(address, chain_id, pkg_name, pkg_version, namespaced_asset, ens)
112109

113110

114-
def _process_pkg_path(raw_pkg_path: str) -> Tuple[Optional[str], Optional[str], Optional[str]]:
111+
def _process_pkg_path(
112+
raw_pkg_path: str,
113+
) -> Tuple[Optional[str], Optional[str], Optional[str]]:
115114
pkg_path = raw_pkg_path.strip("/")
116115
if not pkg_path:
117116
return None, None, None

ethpm/contract.py

+5-7
Original file line numberDiff line numberDiff line change
@@ -59,9 +59,7 @@ def __init__(self, address: bytes, **kwargs: Any) -> None:
5959
super().__init__(address=address, **kwargs) # type: ignore
6060

6161
@classmethod
62-
def factory(
63-
cls, w3: "Web3", class_name: str = None, **kwargs: Any
64-
) -> Contract:
62+
def factory(cls, w3: "Web3", class_name: str = None, **kwargs: Any) -> Contract:
6563
dep_link_refs = kwargs.get("unlinked_references")
6664
bytecode = kwargs.get("bytecode")
6765
needs_bytecode_linking = False
@@ -97,9 +95,7 @@ def link_bytecode(cls, attr_dict: Dict[str, str]) -> Type["LinkableContract"]:
9795
runtime = apply_all_link_refs(
9896
cls.bytecode_runtime, cls.linked_references, attr_dict
9997
)
100-
linked_class = cls.factory(
101-
cls.w3, bytecode_runtime=runtime, bytecode=bytecode
102-
)
98+
linked_class = cls.factory(cls.w3, bytecode_runtime=runtime, bytecode=bytecode)
10399
if linked_class.needs_bytecode_linking:
104100
raise BytecodeLinkingError(
105101
"Expected class to be fully linked, but class still needs bytecode linking."
@@ -176,6 +172,8 @@ def apply_link_ref(offset: int, length: int, value: bytes, bytecode: bytes) -> b
176172
address = value if is_canonical_address(value) else to_canonical_address(value)
177173
new_bytes = (
178174
# Ignore linting error b/c conflict b/w black & flake8
179-
bytecode[:offset] + address + bytecode[offset + length:] # noqa: E201, E203
175+
bytecode[:offset]
176+
+ address
177+
+ bytecode[offset + length :] # noqa: E201, E203
180178
)
181179
return new_bytes

ethpm/package.py

+7-11
Original file line numberDiff line numberDiff line change
@@ -195,8 +195,8 @@ def contract_types(self) -> List[str]:
195195
"""
196196
All contract types included in this package.
197197
"""
198-
if 'contractTypes' in self.manifest:
199-
return sorted(self.manifest['contractTypes'].keys())
198+
if "contractTypes" in self.manifest:
199+
return sorted(self.manifest["contractTypes"].keys())
200200
else:
201201
raise ValueError("No contract types found in manifest; {self.__repr__()}.")
202202

@@ -306,9 +306,7 @@ def get_contract_instance(self, name: ContractName, address: Address) -> Contrac
306306
contract_kwargs = generate_contract_factory_kwargs(
307307
self.manifest["contractTypes"][name]
308308
)
309-
contract_instance = self.w3.eth.contract(
310-
address=address, **contract_kwargs
311-
)
309+
contract_instance = self.w3.eth.contract(address=address, **contract_kwargs)
312310
# TODO: type ignore may be able to be removed after more of AsyncContract is finished
313311
return contract_instance # type: ignore
314312

@@ -372,9 +370,7 @@ def deployments(self) -> Union["Deployments", Dict[None, None]]:
372370
linked_deployments = get_linked_deployments(deployments)
373371
if linked_deployments:
374372
for deployment_data in linked_deployments.values():
375-
on_chain_bytecode = self.w3.eth.get_code(
376-
deployment_data["address"]
377-
)
373+
on_chain_bytecode = self.w3.eth.get_code(deployment_data["address"])
378374
unresolved_linked_refs = normalize_linked_references(
379375
deployment_data["runtimeBytecode"]["linkDependencies"]
380376
)
@@ -392,15 +388,15 @@ def _get_all_contract_instances(
392388
self, deployments: Dict[str, DeploymentData]
393389
) -> Iterable[Tuple[str, Contract]]:
394390
for deployment_name, deployment_data in deployments.items():
395-
if deployment_data['contractType'] not in self.contract_types:
391+
if deployment_data["contractType"] not in self.contract_types:
396392
raise EthPMValidationError(
397393
f"Contract type: {deployment_data['contractType']} for alias: "
398394
f"{deployment_name} not found. Available contract types include: "
399395
f"{self.contract_types}."
400396
)
401397
contract_instance = self.get_contract_instance(
402-
ContractName(deployment_data['contractType']),
403-
deployment_data['address'],
398+
ContractName(deployment_data["contractType"]),
399+
deployment_data["address"],
404400
)
405401
yield deployment_name, contract_instance
406402

ethpm/tools/__init__.py

+4-1
Original file line numberDiff line numberDiff line change
@@ -1 +1,4 @@
1-
from .get_manifest import get_ethpm_local_manifest, get_ethpm_spec_manifest # noqa: F401
1+
from .get_manifest import ( # noqa: F401
2+
get_ethpm_local_manifest,
3+
get_ethpm_spec_manifest,
4+
)

ethpm/tools/builder.py

+10-6
Original file line numberDiff line numberDiff line change
@@ -408,7 +408,7 @@ def _contract_type(
408408
contract_type_data = all_type_data
409409

410410
if "compiler" in contract_type_data:
411-
compiler_info = contract_type_data.pop('compiler')
411+
compiler_info = contract_type_data.pop("compiler")
412412
contract_type_ref = alias if alias else name
413413
manifest_with_compilers = add_compilers_to_manifest(
414414
compiler_info, contract_type_ref, manifest
@@ -422,7 +422,9 @@ def _contract_type(
422422
["contractTypes", alias],
423423
assoc(contract_type_data, "contractType", name),
424424
)
425-
return assoc_in(manifest_with_compilers, ["contractTypes", name], contract_type_data)
425+
return assoc_in(
426+
manifest_with_compilers, ["contractTypes", name], contract_type_data
427+
)
426428

427429

428430
def add_compilers_to_manifest(
@@ -432,7 +434,7 @@ def add_compilers_to_manifest(
432434
Adds a compiler information object to a manifest's top-level `compilers`.
433435
"""
434436
if "compilers" not in manifest:
435-
compiler_info['contractTypes'] = [contract_type]
437+
compiler_info["contractTypes"] = [contract_type]
436438
return assoc_in(manifest, ["compilers"], [compiler_info])
437439

438440
updated_compiler_info = update_compilers_object(
@@ -443,7 +445,9 @@ def add_compilers_to_manifest(
443445

444446
@to_list
445447
def update_compilers_object(
446-
new_compiler: Dict[str, Any], contract_type: str, previous_compilers: List[Dict[str, Any]]
448+
new_compiler: Dict[str, Any],
449+
contract_type: str,
450+
previous_compilers: List[Dict[str, Any]],
447451
) -> Iterable[Dict[str, Any]]:
448452
"""
449453
Updates a manifest's top-level `compilers` with a new compiler information object.
@@ -528,9 +532,9 @@ def normalize_contract_type(
528532
contract_type_data["evm"]["deployedBytecode"]
529533
)
530534
if "devdoc" in contract_type_data:
531-
yield "devdoc", contract_type_data['devdoc']
535+
yield "devdoc", contract_type_data["devdoc"]
532536
if "userdoc" in contract_type_data:
533-
yield "userdoc", contract_type_data['userdoc']
537+
yield "userdoc", contract_type_data["userdoc"]
534538
# make sure metadata isn't an empty string in solc output
535539
if "metadata" in contract_type_data and contract_type_data["metadata"]:
536540
yield "compiler", normalize_compiler_object(

ethpm/tools/get_manifest.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@
1212

1313
def get_ethpm_spec_manifest(use_case: str, filename: str) -> Dict[str, Any]:
1414
ethpm_spec_dir = get_ethpm_spec_dir()
15-
return json.loads((ethpm_spec_dir / 'examples' / use_case / filename).read_text())
15+
return json.loads((ethpm_spec_dir / "examples" / use_case / filename).read_text())
1616

1717

1818
def get_ethpm_local_manifest(use_case: str, filename: str) -> Dict[str, Any]:

ethpm/uri.py

+3-1
Original file line numberDiff line numberDiff line change
@@ -109,7 +109,9 @@ def create_latest_block_uri(w3: "Web3", from_blocks_ago: int = 3) -> URI:
109109
"""
110110
chain_id = to_hex(get_genesis_block_hash(w3))
111111
latest_block_tx_receipt = w3.eth.get_block("latest")
112-
target_block_number = BlockNumber(latest_block_tx_receipt["number"] - from_blocks_ago)
112+
target_block_number = BlockNumber(
113+
latest_block_tx_receipt["number"] - from_blocks_ago
114+
)
113115
if target_block_number < 0:
114116
raise Exception(
115117
f"Only {latest_block_tx_receipt['number']} blocks avaible on provided w3, "

ethpm/validation/manifest.py

+1-3
Original file line numberDiff line numberDiff line change
@@ -112,9 +112,7 @@ def validate_manifest_deployments(manifest: Dict[str, Any]) -> None:
112112
all_contract_types = manifest["contractTypes"].keys()
113113
all_deployments = manifest["deployments"].values()
114114
all_deployment_names = extract_contract_types_from_deployments(all_deployments)
115-
missing_contract_types = all_deployment_names.difference(
116-
all_contract_types
117-
)
115+
missing_contract_types = all_deployment_names.difference(all_contract_types)
118116
if missing_contract_types:
119117
raise EthPMValidationError(
120118
f"Manifest missing references to contracts: {missing_contract_types}."

ethpm/validation/uri.py

+5-3
Original file line numberDiff line numberDiff line change
@@ -72,7 +72,9 @@ def validate_registry_uri(uri: str) -> None:
7272
if pkg_name:
7373
validate_package_name(pkg_name)
7474
if not pkg_name and pkg_version:
75-
raise EthPMValidationError("Registry URIs cannot provide a version without a package name.")
75+
raise EthPMValidationError(
76+
"Registry URIs cannot provide a version without a package name."
77+
)
7678
if pkg_version:
7779
validate_escaped_string(pkg_version)
7880

@@ -88,9 +90,9 @@ def validate_registry_uri_authority(auth: str) -> None:
8890
f"{auth} is not a valid registry URI authority. "
8991
"Please try again with a valid registry URI."
9092
)
91-
address, chain_id = auth.split(':')
93+
address, chain_id = auth.split(":")
9294
else:
93-
address, chain_id = auth, '1'
95+
address, chain_id = auth, "1"
9496

9597
if is_ens_domain(address) is False and not is_checksum_address(address):
9698
raise EthPMValidationError(

newsfragments/2345.misc.rst

+1
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Add black linting to ethpm module

pyproject.toml

+7
Original file line numberDiff line numberDiff line change
@@ -35,3 +35,10 @@ showcontent=true
3535
directory = "misc"
3636
name="Misc"
3737
showcontent=false
38+
39+
[tool.isort]
40+
profile = "black"
41+
42+
[flake8]
43+
max-line-length=88
44+
extend-ignore="E203"

setup.py

+1
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010
"py-geth>=3.8.0,<4",
1111
],
1212
'linter': [
13+
"black>=22.1.0,<23.0",
1314
"flake8==3.8.3",
1415
"isort>=4.2.15,<4.3.5",
1516
"mypy==0.910",

tox.ini

+1
Original file line numberDiff line numberDiff line change
@@ -64,6 +64,7 @@ basepython=python
6464
extras=linter
6565
commands=
6666
flake8 {toxinidir}/web3 {toxinidir}/ens {toxinidir}/ethpm {toxinidir}/tests --exclude {toxinidir}/ethpm/ethpm-spec
67+
black {toxinidir}/ethpm --exclude {toxinidir}/ethpm/ethpm-spec --check
6768
isort --recursive --check-only --diff {toxinidir}/web3/ {toxinidir}/ens/ {toxinidir}/ethpm/ {toxinidir}/tests/
6869
mypy -p web3 -p ethpm -p ens --config-file {toxinidir}/mypy.ini
6970

0 commit comments

Comments
 (0)