Skip to content

Commit

Permalink
Fix some thing with the load and "comment edit" commands.
Browse files Browse the repository at this point in the history
  • Loading branch information
tage64 committed Aug 4, 2023
1 parent 1199313 commit b5b1436
Showing 1 changed file with 32 additions and 28 deletions.
60 changes: 32 additions & 28 deletions chess_cli/__init__.py
Expand Up @@ -333,29 +333,26 @@ def init_games(self, file_name: Optional[str]) -> None:

def load_games(self, file_name: str) -> None:
try:
pgn_file = open(file_name)
games: list[GameHandle] = []
while True:
offset: int = pgn_file.tell()
headers = chess.pgn.read_headers(pgn_file)
if headers is None:
break
games.append(GameHandle(headers, offset))
if not games:
self.poutput(f"Error: Couldn't find any game in {file_name}")
raise CommandFailure()
except Exception as ex:
pgn_file.close()
raise ex
with open(file_name) as pgn_file:
games: list[GameHandle] = []
while True:
offset: int = pgn_file.tell()
headers = chess.pgn.read_headers(pgn_file)
if headers is None:
break
games.append(GameHandle(headers, offset))
if not games:
self.poutput(f"Error: Couldn't find any game in {file_name}")
raise CommandFailure()
# Reset analysis.
self.stop_engines()
self.init_analysis()
self.games = games
self.pgn_file = pgn_file
self.select_game(0)
self.poutput(f"Successfully loaded {len(self.games)} game(s).")
except OSError as ex:
self.poutput(f"Error: Loading of {file_name} failed: {ex}")
else:
# Reset analysis.
self.stop_engines()
self.init_analysis()
self.games = games
self.pgn_file = pgn_file
self.select_game(0)

def stop_engines(self) -> None:
"Stop all running analysis."
Expand Down Expand Up @@ -869,13 +866,20 @@ def set_comment(new_comment: str) -> None:
case "append":
set_comment(comment + " " + args.comment)
case "edit":
with tempfile.NamedTemporaryFile(mode="w+") as file:
file.write(comment)
file.flush()
self.do_shell(f"{self.editor} '{file.name}'")
file.seek(0)
new_comment: str = file.read().strip()
set_comment(new_comment)
fd, file_name = tempfile.mkstemp(suffix=".txt", text=True)
try:
with os.fdopen(fd, mode="w") as file:
file.write(comment)
file.flush()
self.poutput(f"Opening {file_name} in your editor.")
self.onecmd(f"edit '{file_name}'")
with open(file_name, mode="r") as file:
file.seek(0)
new_comment: str = file.read().strip()
set_comment(new_comment)
self.poutput("Successfully updated comment.")
finally:
os.remove(file_name)
case _:
assert False, "Unknown subcommand."

Expand Down

0 comments on commit b5b1436

Please sign in to comment.