patch2vimedit/patch2vimedit/vim_session.py

55 lines
1.7 KiB
Python

import sys
class VimSession:
""" A Vim session instrumented through tmux """
def __init__(self, tmux_session, file_path=None):
self.tmux_session = tmux_session
self.file_path = file_path
self.tmux_session.type_keys("vim")
if self.file_path:
self.tmux_session.type_keys(" {}".format(self.file_path))
self.tmux_session.type_keys("enter")
self.tmux_session.send_keys(":set paste", "enter")
def edit_file(self, file_path):
self.tmux_session.type_keys("escape", ":e ", file_path, "enter")
self.file_path = file_path
def apply_patchset(self, patchset):
for patch in patchset:
self.apply_patch(patch)
def apply_patch(self, patch):
source = patch.source.decode("utf8")
target = patch.target.decode("utf8")
if source != target:
self.tmux_session.type_keys(
"escape", ":!mv ", source, " ", target, "enter",
)
if self.file_path != target:
self.edit_file(target)
for hunk in patch:
self.apply_hunk(hunk)
self.tmux_session.type_keys("escape", ":w", "enter")
def apply_hunk(self, hunk):
# So far, very naive.
self.tmux_session.type_keys("escape", "{}G0".format(hunk.starttgt))
for b_line in hunk.text:
line = b_line.decode("utf8")
if line[0] == " ":
self.tmux_session.type_keys("j")
elif line[0] == "-":
self.tmux_session.type_keys("dd")
elif line[0] == "+":
self.tmux_session.type_keys("O", line.strip()[1:], "escape", "j")
def quit(self):
self.tmux_session.type_keys("escape", ":q", "enter")