Skip to content

Commit

Permalink
Fix msg-filename kept open after edition (#491)
Browse files Browse the repository at this point in the history
--msg-filename type is now a Path and not a managed click.File.
This makes it easier to control the opening and closing of the file.

Context manager will make sure that the file we use will be refreshed after
edition.

Co-authored-by: Maxime Roussin-Bélanger <maxime.roussinbelanger@gmail.com>
  • Loading branch information
jorisroovers and Lorac authored May 2, 2023
1 parent 2a48cda commit 2a77afd
Showing 1 changed file with 8 additions and 9 deletions.
17 changes: 8 additions & 9 deletions gitlint-core/gitlint/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import stat
import sys
from dataclasses import dataclass
from pathlib import Path
from typing import Optional

import click
Expand Down Expand Up @@ -185,7 +186,8 @@ def from_commit_msg(message):
# 1. Any data specified via --msg-filename
if msg_filename:
LOG.debug("Using --msg-filename.")
return from_commit_msg(str(msg_filename.read()))
with msg_filename.open(encoding=gitlint.utils.FILE_ENCODING) as msg_file:
return from_commit_msg(str(msg_file.read()))

# 2. Any data sent to stdin (unless stdin is being ignored)
if not lint_config.ignore_stdin:
Expand Down Expand Up @@ -245,7 +247,7 @@ class ContextObj:
config_builder: LintConfigBuilder
commit_hash: str
refspec: str
msg_filename: str
msg_filename: Optional[Path] = None
gitcontext: Optional[GitContext] = None


Expand All @@ -270,7 +272,7 @@ class ContextObj:
@click.option("--ignore", envvar="GITLINT_IGNORE", default="", help="Ignore rules (comma-separated by id or name).")
@click.option("--contrib", envvar="GITLINT_CONTRIB", default="",
help="Contrib rules to enable (comma-separated by id or name).")
@click.option("--msg-filename", type=click.File(encoding=gitlint.utils.FILE_ENCODING),
@click.option("--msg-filename", type=click.Path(exists=True, dir_okay=False, path_type=Path),
help="Path to a file containing a commit-msg.")
@click.option("--ignore-stdin", envvar="GITLINT_IGNORE_STDIN", is_flag=True,
help="Ignore any stdin data. Useful for running in CI server.")
Expand Down Expand Up @@ -458,13 +460,10 @@ def run_hook(ctx):
exit_code = GITLINT_SUCCESS
elif value == "e":
LOG.debug("run-hook: editing commit message")
msg_filename = ctx.obj.msg_filename
if msg_filename:
msg_filename.seek(0)
if ctx.obj.msg_filename:
editor = os.environ.get("EDITOR", DEFAULT_COMMIT_MSG_EDITOR)
msg_filename_path = os.path.realpath(msg_filename.name)
LOG.debug("run-hook: %s %s", editor, msg_filename_path)
shell(editor + " " + msg_filename_path)
LOG.debug("run-hook: %s %s", editor, ctx.obj.msg_filename)
shell(f"{editor} {ctx.obj.msg_filename}")
else:
click.echo("Editing only possible when --msg-filename is specified.")
ctx.exit(exit_code)
Expand Down

0 comments on commit 2a77afd

Please sign in to comment.