Skip to content
Myr

clean up Editor.edit code

Before adoption: this commit came in with the history the project adopted, so no landing records it.

use context manager for opening file move encoding out of try block use isinstance instead of type

authored by David Lord · committed by David Lord · parent 11c286a · Browse files · 1 file+20 added−21 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

1 file+20 added−21 removed

  • other:+20 added−21 removed

1 file+20 added−21 removed

modified:src/click/_termui_impl.py+20 added-21 removed
472 unmodified lines
473474 def edit(self, text):475 import tempfile476477 text = text or ""478 binary_data = type(text) in [bytes, bytearray]477 if not text:478 text = ""479480 if not binary_data and text and not text.endswith("\n"):481 text += "\n"480 is_bytes = isinstance(text, (bytes, bytearray))481482 if not is_bytes:483 if text and not text.endswith("\n"):484 text += "\n"485486 if WIN:487 text = text.replace("\n", "\r\n").encode("utf-8-sig")488 else:489 text = text.encode("utf-8")490491 fd, name = tempfile.mkstemp(prefix="editor-", suffix=self.extension)492493 try:485 if not binary_data:486 if WIN:487 encoding = "utf-8-sig"488 text = text.replace("\n", "\r\n")489 else:490 encoding = "utf-8"491 text = text.encode(encoding)494 with os.fdopen(fd, "wb") as f:495 f.write(text)496493 f = os.fdopen(fd, "wb")494 f.write(text)495 f.close()497 # If the filesystem resolution is 1 second, like Mac OS498 # 10.12 Extended, or 2 seconds, like FAT32, and the editor499 # closes very fast, require_save can fail. Set the modified500 # time to be 2 seconds in the past to work around this.
6 unmodified lines
507508 if self.require_save and os.path.getmtime(name) == timestamp:509 return None510510 f = open(name, "rb")511 try:511 with open(name, "rb") as f:512 rv = f.read()513 finally:514 f.close()515 if binary_data:513514 if is_bytes:515 return rv517 else:518 return rv.decode("utf-8-sig").replace("\r\n", "\n")516517 return rv.decode("utf-8-sig").replace("\r\n", "\n")518 finally:519 os.unlink(name)520521
152 unmodified lines