Skip to content

Instantly share code, notes, and snippets.

@Qyriad
Created April 5, 2024 02:06
Show Gist options
  • Select an option

  • Save Qyriad/b1c680f01951a17db972b8944f2fd0f3 to your computer and use it in GitHub Desktop.

Select an option

Save Qyriad/b1c680f01951a17db972b8944f2fd0f3 to your computer and use it in GitHub Desktop.
Diff the output of two only slightly different commands. I got annoyed.
#!/usr/bin/env python3
# Assumes that the differing argument is the last one.
import argparse
import os
from pathlib import Path
import shlex
import shutil
import subprocess
import sys
import tempfile
def logcmd(s):
text = s if isinstance(s, str) else shlex.join(s)
return print(f'{text}\x1b[0m', file=sys.stderr)
parser = argparse.ArgumentParser()
parser.add_argument('-d', '--differ', default=os.environ.get('DIFF', 'diff'))
parser.add_argument('template', nargs=argparse.REMAINDER, type=str,
help="% gets replaced with 'before' and 'after', and each is run as a command",
)
args = parser.parse_args()
with tempfile.TemporaryDirectory() as tmpdir:
temp_path = Path(tmpdir)
template_args = args.template
template_args[0] = shutil.which(template_args[0]) or template_args[0]
first_args = [arg.replace('%', 'before') for arg in template_args]
second_args = [arg.replace('%', 'after') for arg in template_args]
first_output = subprocess.check_output(first_args)
logcmd(second_args)
second_output = subprocess.check_output(second_args)
first_path = temp_path / 'first.out'
second_path = temp_path / 'second.out'
with first_path.open('wb') as first_out:
first_out.write(first_output)
with second_path.open('wb') as second_out:
second_out.write(second_output)
diff = shlex.split(args.differ)
diff[0] = shutil.which(diff[0]) or diff[0]
diff_args = [*diff, first_path.as_posix(), second_path.as_posix()]
logcmd(diff_args)
subprocess.call(diff_args)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment