brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: difflib.unified_diff shows what a script changed in a config file

Scripting
~/tips/tip-scripting-difflib-unified-diff

import difflib

Print a diff of two texts from a script, in the same format as git and diff -u.

When a script rewrites a config file, I want it to show what it is about to change, preferably in a format you already know well. difflib produces that without calling an outside diff.

Give it two lists of lines and two names for the header:

import difflib
from pathlib import Path

old = Path("app.conf").read_text().splitlines(keepends=True)
new = render_config().splitlines(keepends=True)

diff = difflib.unified_diff(old, new, fromfile="app.conf", tofile="app.conf (new)")
print("".join(diff), end="")

The output has the familiar --- and +++ header, @@ hunks and lines with - and +. If the result is empty, nothing changed and the script can skip the write. That makes a neat dry run mode.

The same module has get_close_matches, which I find nice for a ‘did you mean’ message when someone mistypes a subcommand: get_close_matches("restrat", ["restart", "status"]) returns ["restart"].

Keep keepends=True when you split, or the output glues lines together. If you split without line ends, pass lineterm="" and join with newlines instead. It is also slow on very large or very different files, since it compares line by line in Python.

Further reading: difflib documentation

More Scripting tips $r = Invoke-RestMethod https://api.github.com/repos/PowerShell/PowerShell/releases/latest import json, os, tempfile from collections import Counter import shutil from contextlib import chdir All Scripting tips (10) All topics

Link