patch2vimedit/patch2vimedit/main.py

141 lines
3.3 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
import logging
logger = logging.getLogger(__name__)
def parse_args():
""" Parse command-line arguments """
parser = argparse.ArgumentParser(prog="patch2vimedit")
parser.add_argument(
"-g",
"--debug",
action="store_true",
help="Enable debug logging to /tmp/patch2log",
)
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
set bg=dark
set number
set ts=4
set sw=4
set et
set so=5
set noautoindent
set nosmartindent
set nocindent
set indentexpr&
"""
)
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 configure_log(args):
if args.debug:
logging.basicConfig(filename="/tmp/patch2log", level=logging.DEBUG)
else:
logging.basicConfig(level=logging.CRITICAL)
logging.getLogger("libtmux").setLevel(logging.INFO)
logging.getLogger("tmux").setLevel(logging.INFO)
def main():
""" Entry-point function """
args = parse_args()
configure_log(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()