Skip to content

Commit

Permalink
Use black autoformatter for pre-commit of python files (#84)
Browse files Browse the repository at this point in the history
* Enable Black for Python code

* Fix some new pylint warnings that weren't caught earlier

* Temporarily ignore warnings on struct.* on Python 3.9

* Run black on all files once

pre-commit run -a black

(also moved a few # pylint comments around
  • Loading branch information
mikeage authored Apr 15, 2021
1 parent fbe9985 commit eba58b2
Show file tree
Hide file tree
Showing 37 changed files with 5,659 additions and 4,852 deletions.
4 changes: 3 additions & 1 deletion .editorconfig
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,9 @@ root = true
indent_style = space
indent_size = 2

# Based on Google's C# style guide
[*.py]
indent_size = 4

[*.cs]
indent_size = 4

Expand Down
2 changes: 1 addition & 1 deletion .flake8
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
[flake8]
extend-ignore = E111, E114, E501, E722, E121
extend-ignore = E111, E114, E501, E722, E121, E203, W503
12 changes: 9 additions & 3 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,19 @@ repos:
rev: v1.17.0
hooks:
- id: yamllint
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v2.0.0
- repo: https://github.com/psf/black
rev: 20.8b1
hooks:
- id: black
files: ^Support/
language_version: python3
- repo: https://github.com/pycqa/flake8
rev: 3.9.0
hooks:
- id: flake8
files: ^Support/
- repo: https://github.com/PyCQA/pylint.git
rev: pylint-2.6.0
rev: pylint-2.7.4
hooks:
- id: pylint
name: pylint
Expand Down
4 changes: 4 additions & 0 deletions .pylintrc
Original file line number Diff line number Diff line change
@@ -1,2 +1,6 @@
[MESSAGES CONTROL]
disable=bad-indentation,missing-class-docstring,missing-module-docstring,missing-function-docstring,invalid-name,fixme,line-too-long,duplicate-code

extension-pkg-whitelist=math,zlib,struct
# Temporary, until https://github.com/PyCQA/pylint/issues/4297 is resolved
generated-members=struct.*
102 changes: 53 additions & 49 deletions Support/Python/tbdata/brush_lookup.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,61 +18,65 @@
from typing import cast, Dict, Iterator, List, Tuple, NewType
from collections import defaultdict

Guid = NewType('Guid', str)
Guid = NewType("Guid", str)


class BrushLookup():
"""Helper for doing name <-> guid conversions for brushes."""
class BrushLookup:
"""Helper for doing name <-> guid conversions for brushes."""

def iter_standard_brush_guids(self) -> Iterator[Guid]:
"""Yields all the standard (non-experimental) brush guids"""
with open(os.path.join(self.dir, 'Assets/Manifest.asset')) as inf:
data = inf.read().replace('\r', '')
brush_chunk = re.search(r'Brushes:\n( -.*\n)*', data).group(0)
for match in re.finditer(r'guid: ([0-9a-f]{32})', brush_chunk):
yield cast(Guid, match.group(1))
def iter_standard_brush_guids(self) -> Iterator[Guid]:
"""Yields all the standard (non-experimental) brush guids"""
with open(os.path.join(self.dir, "Assets/Manifest.asset")) as inf:
data = inf.read().replace("\r", "")
brush_chunk = re.search(r"Brushes:\n( -.*\n)*", data).group(0)
for match in re.finditer(r"guid: ([0-9a-f]{32})", brush_chunk):
yield cast(Guid, match.group(1))

@staticmethod
def iter_brush_guid_and_name(tilt_brush_dir: str) -> Iterator[Tuple[Guid, str]]:
"""Yields (guid, name) tuples."""
for brush_dir in ("Assets/Resources/Brushes", "Assets/Resources/X/Brushes"):
for r, _, fs in os.walk(os.path.join(tilt_brush_dir, brush_dir)):
for f in fs:
if f.lower().endswith('.asset'):
fullf = os.path.join(r, f)
with open(fullf) as inf:
data = inf.read()
guid = cast(Guid, re.search('m_storage: (.*)$', data, re.M).group(1))
# name = re.search('m_Name: (.*)$', data, re.M).group(1)
name = f[:-6]
yield guid, name
@staticmethod
def iter_brush_guid_and_name(tilt_brush_dir: str) -> Iterator[Tuple[Guid, str]]:
"""Yields (guid, name) tuples."""
for brush_dir in ("Assets/Resources/Brushes", "Assets/Resources/X/Brushes"):
for r, _, fs in os.walk(os.path.join(tilt_brush_dir, brush_dir)):
for f in fs:
if f.lower().endswith(".asset"):
fullf = os.path.join(r, f)
with open(fullf) as inf:
data = inf.read()
guid = cast(
Guid, re.search("m_storage: (.*)$", data, re.M).group(1)
)
# name = re.search('m_Name: (.*)$', data, re.M).group(1)
name = f[:-6]
yield guid, name

_instances: Dict[str, 'BrushLookup'] = {}
_instances: Dict[str, "BrushLookup"] = {}

@classmethod
def get(cls, tilt_brush_dir=None) -> 'BrushLookup':
if tilt_brush_dir is None:
tilt_brush_dir = os.path.normpath(os.path.join(os.path.abspath(__file__), "../../../.."))
@classmethod
def get(cls, tilt_brush_dir=None) -> "BrushLookup":
if tilt_brush_dir is None:
tilt_brush_dir = os.path.normpath(
os.path.join(os.path.abspath(__file__), "../../../..")
)

try:
return cls._instances[tilt_brush_dir]
except KeyError:
pass
val = cls._instances[tilt_brush_dir] = BrushLookup(tilt_brush_dir)
return val
try:
return cls._instances[tilt_brush_dir]
except KeyError:
pass
val = cls._instances[tilt_brush_dir] = BrushLookup(tilt_brush_dir)
return val

def __init__(self, tilt_brush_dir: str):
self.dir = tilt_brush_dir
self.initialized = True
self.guid_to_name = dict(self.iter_brush_guid_and_name(self.dir))
self.standard_brushes = set(self.iter_standard_brush_guids())
name_to_guids: Dict[str, List[Guid]] = defaultdict(list)
for guid, name in self.guid_to_name.items():
name_to_guids[name].append(guid)
self.name_to_guids = dict(name_to_guids)
def __init__(self, tilt_brush_dir: str):
self.dir = tilt_brush_dir
self.initialized = True
self.guid_to_name = dict(self.iter_brush_guid_and_name(self.dir))
self.standard_brushes = set(self.iter_standard_brush_guids())
name_to_guids: Dict[str, List[Guid]] = defaultdict(list)
for guid, name in self.guid_to_name.items():
name_to_guids[name].append(guid)
self.name_to_guids = dict(name_to_guids)

def get_unique_guid(self, name: str) -> Guid:
lst = self.name_to_guids[name]
if len(lst) == 1:
return lst[0]
raise LookupError("%s refers to multiple brushes" % name)
def get_unique_guid(self, name: str) -> Guid:
lst = self.name_to_guids[name]
if len(lst) == 1:
return lst[0]
raise LookupError("%s refers to multiple brushes" % name)
Loading

0 comments on commit eba58b2

Please sign in to comment.