Skip to content

Commit

Permalink
Black (#456)
Browse files Browse the repository at this point in the history
* apply black -S and isort

* add to requirements.txt

* get rid of pycodestyle, run black in ci

* update isort

* disable trailing comma magic

* delete setup.cfg

* several manual fixes
  • Loading branch information
Akuli authored Jun 5, 2021
1 parent b0dbfdd commit 405e533
Show file tree
Hide file tree
Showing 85 changed files with 1,530 additions and 1,059 deletions.
4 changes: 2 additions & 2 deletions .github/workflows/main.yml
Original file line number Diff line number Diff line change
Expand Up @@ -74,15 +74,15 @@ jobs:
- run: $PYTHON -m pip install -r requirements.txt -r requirements-dev.txt
- run: $PYTHON scripts/download-tkdnd.py
- run: $PYTHON -m pytest -vvvv --durations=10
pycodestyle:
black:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: actions/setup-python@v1
with:
python-version: "3.9"
- run: pip install -r requirements-dev.txt
- run: python3 -m pycodestyle scripts/*.py porcupine tests more_plugins
- run: python3 -m black --check scripts/*.py porcupine tests more_plugins
isort:
runs-on: ubuntu-latest
steps:
Expand Down
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -181,6 +181,7 @@ Here is a list of the commands I use when developing Porcupine:
- `mypy porcupine more_plugins`
- `python3 -m pytest` runs tests. You will see lots of weird stuff happening
while testing, and that's expected.
- Code formatting tools: `black porcupine/` and `isort porcupine/`
- To see a report of test coverage, add `--cov=porcupine` to the above pytest
command and then run `coverage html`. Open `htmlcov/index.html` in your favorite
browser to view it. If you don't have anything else to do, you can write more
Expand Down
19 changes: 10 additions & 9 deletions more_plugins/pythonprompt.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,6 @@ def _tupleindex(index: str) -> Tuple[int, int]:


class PythonPrompt:

def __init__(self, textwidget: tkinter.Text, close_callback: Callable[[], None]):
self.widget = textwidget
self.close_callback = close_callback
Expand All @@ -37,8 +36,12 @@ def __init__(self, textwidget: tkinter.Text, close_callback: Callable[[], None])
# without -u python buffers stdout and everything is one enter
# press late :( see python --help
self.process = subprocess.Popen(
[sys.executable, '-i', '-u'], stdin=subprocess.PIPE,
stdout=subprocess.PIPE, stderr=subprocess.STDOUT, bufsize=0)
[sys.executable, '-i', '-u'],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
bufsize=0,
)

# the queuer thread is a daemon thread because it makes exiting
# porcupine easier and interrupting it isn't a problem
Expand Down Expand Up @@ -88,7 +91,7 @@ def _on_return(self, junk: object) -> utils.BreakOrNone:

# this needs to return 'break' to allow pressing enter with the
# cursor anywhere on the line
text = self.widget.get('%d.%d' % end_of_output, 'end') # ends with \n
text = self.widget.get('%d.%d' % end_of_output, 'end') # ends with \n
self.widget.insert('end', '\n')
self.widget.mark_set('insert', 'end')
assert self.process.stdin is not None
Expand Down Expand Up @@ -121,24 +124,22 @@ def _queue_clearer(self) -> None:
self.close_callback()
else:
self.widget.insert(
'end', "\n\n***********************\n" +
f"the subprocess exited with code {value!r}")
'end', f"\n\n***********************\nthe subprocess exited with code {value!r}"
)
self.widget.config(state='disabled')
return

assert state == 'output' and isinstance(value, bytes)
if sys.platform == 'win32':
value = value.replace(b'\r\n', b'\n')
self.widget.insert(
'end-1c', value.decode('utf-8', errors='replace'), 'output')
self.widget.insert('end-1c', value.decode('utf-8', errors='replace'), 'output')
self.widget.see('end-1c')

# we got something, let's try again as soon as possible
self.widget.after_idle(self._queue_clearer)


class PromptTab(tabs.Tab):

def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
self.title_choices = ["Interactive Prompt"]
Expand Down
12 changes: 6 additions & 6 deletions more_plugins/terminal.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,14 +14,14 @@ def start_xterm() -> None:
tab = tabs.Tab(get_tab_manager())
tab.title_choices = ["Terminal"]
content = tkinter.Frame(tab, container=True)
content.pack(fill='both', expand=True) # FIXME: doesn't stretch correctly?
content.pack(fill='both', expand=True) # FIXME: doesn't stretch correctly?

try:
process = subprocess.Popen(['xterm', '-into', str(content.winfo_id())])
except FileNotFoundError:
messagebox.showerror("xterm not found", (
"Seems like xterm is not installed. " +
"Please install it and try again."))
messagebox.showerror(
"xterm not found", "Seems like xterm is not installed. Please install it and try again."
)
return

def terminal_wants_to_exit(junk: object) -> None:
Expand All @@ -38,8 +38,8 @@ def setup() -> None:
if get_tab_manager().tk.call('tk', 'windowingsystem') != 'x11':
# TODO: more noob-friendly "u have the wrong os lel" message?
messagebox.showerror(
"Unsupported windowing system",
"Sorry, the terminal plugin only works on X11 :(")
"Unsupported windowing system", "Sorry, the terminal plugin only works on X11 :("
)
return

menubar.get_menu("Tools").add_command(label="Terminal", command=start_xterm)
69 changes: 35 additions & 34 deletions more_plugins/tetris.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@

WIDTH = 10
HEIGHT = 20
SCALE = 20 # each square is 20x20 pixels
SCALE = 20 # each square is 20x20 pixels

Point = Tuple[int, int]
ShapeLetter = str
Expand All @@ -22,6 +22,7 @@
# shape is added to it
# y is like in math, so more y means higher
SHAPES: Dict[ShapeLetter, List[Point]] = {
# fmt: off
'I': [(0, 2),
(0, 1),
(0, 0),
Expand All @@ -34,14 +35,15 @@
(0, 0),
(0, -1), (1, -1)],
'J': [
(0, 1), # noqa
(0, 1),
(0, 0),
(-1, -1), (0, -1)], # noqa
(-1, -1), (0, -1)],
'S': [
(0, 1), (1, 1), # noqa
(-1, 0), (0, 0)], # noqa
(0, 1), (1, 1),
(-1, 0), (0, 0)],
'Z': [(-1, 1), (0, 1),
(0, 0), (1, 0)],
# fmt: on
}


Expand All @@ -67,7 +69,7 @@ def get_coords(self) -> Iterator[Point]:
yield (self.x + shapex, self.y + shapey)

def bumps(self, x: int, y: int) -> bool:
return (x not in range(WIDTH) or y < 0 or (x, y) in self._game.frozen_squares)
return x not in range(WIDTH) or y < 0 or (x, y) in self._game.frozen_squares

def _move(self, deltax: int, deltay: int) -> bool:
for x, y in self.get_coords():
Expand Down Expand Up @@ -99,7 +101,6 @@ def rotate(self) -> bool:


class NonRotatingBlock(Block):

def rotate(self) -> bool:
return False

Expand Down Expand Up @@ -138,14 +139,14 @@ class Game:

def __init__(self) -> None:
self.frozen_squares: Dict[Point, str] = {}
self.score = 0 # each new block increments score
self.add_block() # creates self.moving_block
self.paused = False # only used outside this class definition
self.score = 0 # each new block increments score
self.add_block() # creates self.moving_block
self.paused = False # only used outside this class definition

@property
def level(self) -> int:
# levels start at 1
return self.score//30 + 1 # noqa
return self.score // 30 + 1

@property
def delay(self) -> int:
Expand Down Expand Up @@ -178,8 +179,7 @@ def delete_full_lines(self) -> None:
# this is much easier with a nested list
lines = []
for y in range(HEIGHT):
line = [self.frozen_squares.pop((x, y), None)
for x in range(WIDTH)]
line = [self.frozen_squares.pop((x, y), None) for x in range(WIDTH)]
if None in line:
# it's not full, we can keep it
lines.append(line)
Expand Down Expand Up @@ -215,32 +215,31 @@ def game_over(self) -> bool:


class TetrisTab(tabs.Tab):

def __init__(self, manager: tabs.TabManager) -> None:
super().__init__(manager)
self.title_choices = ["Tetris"]

# the takefocus thing is important, it's hard to bind the keys
# correctly without it
self._canvas = tkinter.Canvas(
self, width=WIDTH*SCALE, height=HEIGHT*SCALE,
relief='ridge', bg='black', takefocus=True)
self,
width=WIDTH * SCALE,
height=HEIGHT * SCALE,
relief='ridge',
bg='black',
takefocus=True,
)
self._canvas.pack()

self._score_label = ttk.Label(self, justify='center')
self._score_label.pack()

help_text = ' '.join(f'''
You can move the blocks with arrow keys.
Press {utils.get_binding('<<Tetris:Pause>>')} to pause
or {utils.get_binding('<<Tetris:NewGame>>')} to start a new game.
'''.split())
ttk.Label(
self,
text=help_text,
justify='center',
wraplength=self._canvas['width'],
).pack()
help_text = (
"You can move the blocks with arrow keys. "
f"Press {utils.get_binding('<<Tetris:Pause>>')} to pause "
f"or {utils.get_binding('<<Tetris:NewGame>>')} to start a new game."
)
ttk.Label(self, text=help_text, justify='center', wraplength=self._canvas['width']).pack()

for key in ['<Left>', '<Right>', '<Up>', '<Down>', '<Return>', '<space>']:
self._canvas.bind(key, self._on_key, add=True)
Expand All @@ -254,8 +253,8 @@ def __init__(self, manager: tabs.TabManager) -> None:
left = x * SCALE
bottom = (HEIGHT - y) * SCALE
self._canvas_content[(x, y)] = self._canvas.create_rectangle(
left, bottom - SCALE, left + SCALE, bottom,
outline='black', fill='black')
left, bottom - SCALE, left + SCALE, bottom, outline='black', fill='black'
)

self._timeout_id: Optional[str] = None
self._game_over_id: Optional[int] = None
Expand Down Expand Up @@ -298,7 +297,8 @@ def _refresh(self) -> None:
self._canvas.itemconfig(item_id, fill=color)

self._score_label['text'] = f"Score {self._game.score}, level {self._game.level}\n" + (
"Paused" if self._game.paused else "")
"Paused" if self._game.paused else ""
)

def new_game(self) -> None:
if self._timeout_id is not None:
Expand All @@ -322,10 +322,11 @@ def _on_timeout(self) -> None:
font_size = 18

self._canvas.create_rectangle(
0, centery - font_size, self._canvas['width'], centery + font_size,
fill='black')
0, centery - font_size, self._canvas['width'], centery + font_size, fill='black'
)
self._game_over_id = self._canvas.create_text(
centerx, centery,
centerx,
centery,
anchor='center',
text="Game Over :(",
font=('', font_size, 'bold'),
Expand All @@ -336,7 +337,7 @@ def _on_timeout(self) -> None:
self._timeout_id = self.after(self._game.delay, self._on_timeout)

def get_state(self) -> Game:
return self._game # it should be picklable
return self._game # it should be picklable

@classmethod
def from_state(cls, manager: tabs.TabManager, game: Game) -> 'TetrisTab':
Expand Down
4 changes: 2 additions & 2 deletions porcupine/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@

import appdirs # type: ignore[import]

version_info = (0, 92, 4) # this is updated with scripts/release.py
version_info = (0, 92, 4) # this is updated with scripts/release.py
__version__ = '%d.%d.%d' % version_info
__author__ = 'Akuli'
__copyright__ = 'Copyright (c) 2017-2021 Akuli'
Expand All @@ -29,7 +29,7 @@

get_main_window = _state.get_main_window
get_parsed_args = _state.get_parsed_args
get_paned_window = _state.get_paned_window # TODO: document this
get_paned_window = _state.get_paned_window # TODO: document this
get_tab_manager = _state.get_tab_manager
filedialog_kwargs = _state.filedialog_kwargs
quit = _state.quit
Loading

0 comments on commit 405e533

Please sign in to comment.