Skip to content

Commit 8a0af85

Browse files
committed
feat(commands/commit): add force-edit functionality after answering questions
1 parent 00d2d96 commit 8a0af85

File tree

3 files changed

+37
-0
lines changed

3 files changed

+37
-0
lines changed

commitizen/cli.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -162,6 +162,12 @@ def __call__(
162162
"default": 0,
163163
"help": "length limit of the commit message; 0 for no limit",
164164
},
165+
{
166+
"name": ["-e", "--edit"],
167+
"action": "store_true",
168+
"default": False,
169+
"help": "force edit the commit message in the editor",
170+
},
165171
],
166172
},
167173
{

commitizen/commands/commit.py

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,9 @@
22

33
import contextlib
44
import os
5+
import shutil
6+
import subprocess
7+
import tempfile
58

69
import questionary
710

@@ -72,9 +75,27 @@ def prompt_commit_questions(self) -> str:
7275

7376
return message
7477

78+
def force_edit(self, message: str) -> str:
79+
editor = git.get_core_editor()
80+
if editor is None:
81+
raise RuntimeError("No 'editor' value given and no default available.")
82+
exec_path = shutil.which(editor)
83+
if exec_path is None:
84+
raise RuntimeError(f"Editor '{editor}' not found.")
85+
with tempfile.NamedTemporaryFile(mode="w", delete=False) as file:
86+
file.write(message)
87+
file_path = file.name
88+
argv = [exec_path, file_path]
89+
subprocess.call(argv)
90+
with open(file_path) as temp_file:
91+
message = temp_file.read().strip()
92+
os.remove(file_path)
93+
return message
94+
7595
def __call__(self):
7696
dry_run: bool = self.arguments.get("dry_run")
7797
write_message_to_file: bool = self.arguments.get("write_message_to_file")
98+
force_edit: bool = self.arguments.get("edit")
7899

79100
is_all: bool = self.arguments.get("all")
80101
if is_all:
@@ -101,6 +122,9 @@ def __call__(self):
101122
else:
102123
m = self.prompt_commit_questions()
103124

125+
if force_edit:
126+
m = self.force_edit(m)
127+
104128
out.info(f"\n{m}\n")
105129

106130
if write_message_to_file:

commitizen/git.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -271,6 +271,13 @@ def get_eol_style() -> EOLTypes:
271271
return map["native"]
272272

273273

274+
def get_core_editor() -> str | None:
275+
c = cmd.run("git var GIT_EDITOR")
276+
if c.out:
277+
return c.out.strip()
278+
return None
279+
280+
274281
def smart_open(*args, **kargs):
275282
"""Open a file with the EOL style determined from Git."""
276283
return open(*args, newline=get_eol_style().get_eol_for_open(), **kargs)

0 commit comments

Comments
 (0)