vimtabdiff/vimtabdiff.py

72 lines
2.2 KiB
Python
Raw Normal View History

2022-11-30 11:59:52 -05:00
#!/usr/bin/python3
import os,sys
2022-12-04 18:22:45 -05:00
import argparse
import pathlib
2022-12-04 19:21:14 -05:00
import itertools
2022-12-05 13:55:05 -05:00
import tempfile
import subprocess
2022-12-04 18:22:45 -05:00
2022-12-05 20:13:31 -05:00
def star(f):
""" see https://stackoverflow.com/q/21892989 """
return lambda args: f(*args)
2022-12-04 18:22:45 -05:00
def parse_args():
parser = argparse.ArgumentParser(description="Show diff in vim tab pages")
parser.add_argument("pathA")
parser.add_argument("pathB")
2022-12-05 20:13:31 -05:00
parser.add_argument("--vim", help="vim command to run", default="vim")
2022-12-04 18:22:45 -05:00
return parser.parse_args()
2022-12-05 13:55:05 -05:00
def get_dir_info(dirname):
2022-12-04 18:22:45 -05:00
if not dirname:
return [],[]
dirs, files = [], []
2022-12-05 13:55:05 -05:00
dirp = pathlib.Path(dirname)
for p in dirp.iterdir():
2022-12-04 18:22:45 -05:00
if p.is_dir():
dirs.append(p)
else:
files.append(p)
return dirs, files
2022-12-04 19:36:51 -05:00
def get_pairs(aItems, bItems):
2022-12-04 19:21:14 -05:00
aItems = [(item, 'A') for item in aItems]
bItems = [(item, 'B') for item in bItems]
2022-12-05 13:55:05 -05:00
abItems = aItems + bItems
2022-12-05 20:13:31 -05:00
abItems.sort(key=star(lambda item, tag: (item.name, tag)))
for _, items in itertools.groupby(abItems, key=star(lambda item, _: item.name)):
items = list(items) # NOTE: python 3.10's match expression can make this better
2022-12-04 19:21:14 -05:00
if len(items) == 2:
2022-12-04 19:36:51 -05:00
(aItem, _), (bItem, _) = items
2022-12-04 19:21:14 -05:00
yield aItem, bItem
else:
2022-12-04 19:36:51 -05:00
(item, tag), = items
2022-12-04 19:21:14 -05:00
if tag == 'A':
yield item, None
else:
yield None, item
2022-12-04 18:22:45 -05:00
def get_file_pairs(a, b):
2022-12-05 13:55:05 -05:00
aDirs, aFiles = get_dir_info(a)
bDirs, bFiles = get_dir_info(b)
2022-12-04 19:36:51 -05:00
yield from get_pairs(aFiles, bFiles)
for aDir, bDir in get_pairs(aDirs, bDirs):
2022-12-04 19:21:14 -05:00
yield from get_file_pairs(aDir, bDir)
2022-11-30 11:59:52 -05:00
def main():
2022-12-04 18:22:45 -05:00
args = parse_args()
2022-12-05 13:55:05 -05:00
vimCmdFile = tempfile.NamedTemporaryFile(mode='w', delete=False)
with vimCmdFile:
for a, b in get_file_pairs(args.pathA, args.pathB):
2022-12-05 20:13:31 -05:00
aPath = a.resolve() if a else "/dev/null"
bPath = b.resolve() if b else "/dev/null"
print(f"tabedit {aPath} | diffthis | vsp {bPath} | diffthis | diffupdate", file=vimCmdFile)
print("tabrewind | bdelete", file=vimCmdFile)
2022-12-05 13:55:05 -05:00
print(f"""call delete("{vimCmdFile.name}")""", file=vimCmdFile)
2022-12-05 20:13:31 -05:00
subprocess.run(args.vim.split() + ["-S", vimCmdFile.name])
2022-11-30 11:59:52 -05:00
if __name__ == '__main__':
main()
2022-12-04 19:36:51 -05:00