patch2vimedit/patch2vimedit/main.py

107 lines
2.8 KiB
Python

import argparse
import pathlib
import os
import sys
import time
import tempfile
import patch
from tmux import TmuxSession
from vim_session import VimSession
def parse_args():
""" Parse command-line arguments """
parser = argparse.ArgumentParser(prog="patch2vimedit")
parser.add_argument(
"-C",
"--directory",
metavar="DIR",
help="Change to DIR before performing any operations.",
)
parser.add_argument(
"patch",
help=(
"The patch file to be applied. If '-' is supplied, reads from STDIN "
"instead."
),
)
return parser.parse_args()
def get_patch(patch_path):
if patch_path == "-":
return patch.PatchSet(sys.stdin)
with open(patch_path, "rb") as stream:
return patch.PatchSet(stream)
def configure_home(home):
""" Configures the temporary home """
tmux_conf_path = home / ".tmux.conf"
vim_conf_path = home / ".vimrc"
print("Configuring tmux in {}".format(tmux_conf_path))
with tmux_conf_path.open("w") as tmux_conf:
tmux_conf.write("set -g status off\n")
with vim_conf_path.open("w") as vim_conf:
vim_conf.write(
"syntax on\nset bg=dark\nset number\nset ts=4\nset sw=4\nset et\n"
)
return tmux_conf_path, vim_conf_path
def apply_patchset(patchset):
tmux_session = TmuxSession.create_detached()
tmux_fg_process = tmux_session.process_attach(read_only=True)
time.sleep(0.2)
vim_session = VimSession(tmux_session)
time.sleep(0.2)
vim_session.apply_patchset(patchset)
time.sleep(1)
vim_session.quit()
time.sleep(0.5)
tmux_session.type_keys("exit", "enter")
tmux_fg_process.join(1)
if tmux_fg_process.exitcode is None: # Did not terminate -- kill it
tmux_fg_process.kill()
if tmux_session.session_exists():
tmux_session.session.kill_session()
def main():
""" Entry-point function """
args = parse_args()
patchset = get_patch(args.patch)
if args.directory:
chdir_to = pathlib.Path(args.directory)
if not chdir_to.is_dir():
print(
(
"The required working directory '{}' does not exist, or is not a "
"directory."
).format(str(chdir_to)),
file=sys.stderr,
)
sys.exit(1)
os.chdir(chdir_to)
with tempfile.TemporaryDirectory() as tmp_home_path:
os.environ["HOME"] = tmp_home_path
tmp_home = pathlib.Path(tmp_home_path)
tmux_conf, _ = configure_home(tmp_home)
TmuxSession.initialize_server(
socket_name="patch2vimedit", config_file=tmux_conf.as_posix()
)
apply_patchset(patchset)
if __name__ == "__main__":
main()