Created
April 5, 2019 06:40
-
-
Save czocher/42f2b5086fffb6902b889cfe21202103 to your computer and use it in GitHub Desktop.
Contextmanager which opens the default editor on a given text and lets you edit it, then returns the result
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os | |
import tempfile | |
from subprocess import call | |
EDITOR = os.environ.get('EDITOR', 'vi') | |
class Editor: | |
def __init__(self, text): | |
self.text = text | |
# Set a default result | |
self.result = text | |
def open(self): | |
with tempfile.NamedTemporaryFile(suffix='.tmp') as temp: | |
temp.write(self.text.encode('utf-8')) | |
temp.flush() | |
call([EDITOR, temp.name]) | |
temp.seek(0) | |
self.result = temp.read().decode('utf-8') | |
@staticmethod | |
def _is_comment(line): | |
return line.startswith('#') | |
@property | |
def is_edited(self): | |
return self.text != self.result | |
@property | |
def is_empty(self): | |
# Filter out empty lines and comments (starting with #) | |
return len(list(filter(lambda line: line and not line.startswith('#'), self.result.split('\n')))) == 0 | |
def __enter__(self): | |
return self | |
def __exit__(self, exc_type, exc_val, exc_tb): | |
pass |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment