Skip to content

Git and Diffs

rafageist edited this page Dec 3, 2026 · 5 revisions

Git and Diffs

Use it for reading and changing a repository (turboframe.git), showing a diff (DiffView), a Git menu with its windows (GitMixin)
Import from turboframe import git; from turboframe.ui.diffview import DiffView; from turboframe.ui.git import GitMixin
Needs the git program on the PATH; nothing more to install
Extend GIT_FEATURES, GIT_REFRESH and the mixin's hooks; DiffView.store, DiffView.syntax

The git service

turboframe.git runs the system's git, as a person would in a terminal. It reads what git prints in its machine formats (status --porcelain=v2, log with separators, for-each-ref, blame --porcelain) into plain dataclasses, and lets git make every change, with its output line by line. It never asks anything: prompts are off (quiet_env()), and git runs in a session of its own, so ssh cannot ask for a passphrase on your screen. A remote that needs one fails and says so, and an ssh agent or a credential helper answers for you.

from pathlib import Path

from turboframe import git

root = git.find_root(Path.cwd())             # the folder with .git, without running git
status = await git.status(root)
print(status.branch, status.ahead, status.behind)
for change in status.changes:                # Change(area, path, code, orig)
    print(change.area, change.code, change.path)   # area: staged, changes, untracked or conflicts
text = await git.diff_of(root, status.changes[0])
Reading
status(root, ignored=False) Status: branch, upstream, ahead, behind, changes; marks(status, root) turns it into a tree's marks
log(root, limit=400, path=None, everything=True) Commits, with the graph
details(root, oid) a commit's message and files
blame(root, path, contents=None) BlameLines: who changed each line (contents: an editor's unsaved text)
diff_of(root, change), diff_of_commit(root, oid), head_text(root, path) diffs and the last committed text
branches(root), remotes(root), stashes(root)
parse_diff(text) a Diff: its DiffFiles, their Hunks and numbered DiffLines
Changing
stage, unstage, discard the index and the working tree
commit(root, message, amend=False, on_line=None) its hooks' output to on_line
switch, create_branch, delete_branch
fetch(root), pull(root), push(root, status) with on_line and on_progress, as process.run
merge, abort_merge, merging, stash, unstash, drop_stash

A failure raises GitError with git's own message. git.program() is None when git is not installed: check it before offering a Git menu.

The diff viewer

DiffView (turboframe.ui.diffview) draws a diff as a code review shows it. Each file sits under a bar with its path and +N -M. Each hunk has a row saying where it starts and which function it is in. Each line has its old and new numbers, on red (removed), green (added) or the editor's colour, and inside a changed line the words that changed are in a stronger shade.

Unified Side by side
Unified Side by side

Keys: Up, Down, PgUp, PgDn, Home, End; Left and Right scroll sideways; N and P go to the next and previous hunk; S switches between unified and side by side; Enter posts DiffView.LineChosen(path, line).

from turboframe.ui.diffview import DiffView

view = DiffView()                          # a widget: yield it from a window's compose_content()
view.show(diff_text)                       # a diff
view.show(file_text, conflict=True)        # a file in conflict: git's markers, ours, theirs
view.show_message("Nothing to compare.")

Two class attributes connect it to your application, once:

  • DiffView.store = settings keeps the side-by-side choice, under "git_diff_side_by_side" (load() and save(); see Settings and Recent Files).
  • DiffView.syntax = fn gives the code your editor's colours: fn(path, text) returns, per line, (start, end, token kind). highlight_spans(text_area, text) reads them from a Textual TextArea with a language.

API: turboframe.git, turboframe.ui.diffview.

The git windows

turboframe.ui.git gives a desktop Turbo Pascal-style windows over the git service. Mix GitMixin into your DesktopApp (with ExplorerMixin, to mark the tree, and EditorMixin, to open files: see Application Mixins), put git_menu_items() in your menu bar, and send its commands to git_command from a worker:

from textual import work
from textual_vision.menus import Menu, SubMenu

from turboframe.ui.app import DesktopApp
from turboframe.ui.editing import EditorMixin
from turboframe.ui.explorer import ExplorerMixin
from turboframe.ui.git import GIT_COMMANDS, GitMixin


class Workbench(GitMixin, EditorMixin, ExplorerMixin, DesktopApp):
    GIT_FEATURES = frozenset({"blame", "branches", "stash"})    # a narrower Git menu; all of them by default

    def __init__(self, folder) -> None:
        super().__init__()
        self.folder = folder                                     # git_folder() reads it

    def init_menu_bar(self) -> Menu:
        return Menu([SubMenu("~G~it", *self.git_menu_items())])   # the offered commands, in groups

    def on_mount(self) -> None:
        self.call_after_refresh(self.start)

    def start(self) -> None:
        self.show_explorer()
        self.start_git_watch()                                   # the state, every GIT_REFRESH seconds

    def on_command_message(self, message) -> None:
        if message.command in GIT_COMMANDS:
            message.stop()
            self.git(message.command)

    @work(group="command")
    async def git(self, command: int) -> None:
        await self.git_command(command)       # True: the command was Git's (v0.2.1; None in v0.2.0)
Window What it shows
Changes what is staged, changed and untracked, and each file's diff; stage, unstage, discard, commit (or amend)
History the commits, each one's files and diffs; File history: those of the file being edited
Branches branches and stashes: switch, new branch, merge (its conflicts go to Changes), delete, stash, apply, drop
Blame who changed each line last, and that commit
Git what git said, bounded, following its end (a LogWindow, see Log and Output Windows)

The Git menu also has Commit, Pull, Push, Fetch and Diff of the file. The diffs are DiffViews (unified or side by side); fetch, pull and push run under the progress box (see Progress). When git changes files that are open, editors without unsaved changes read them again, and the others are named. The explorer marks changed files and the folders holding them, and its bottom border says the branch and how far it is from its upstream (main ↑1 ↓2); editors mark changed lines in their gutter.

GIT_FEATURES takes any of FEATURES: blame, branches, discard, amend, stash, merge, remote and new_branch. What it leaves out is neither in the menus nor on the windows' keys. frozenset() keeps the windows that read (Changes with stage and commit, History, the diffs) and nothing destructive or remote. GIT_REFRESH (5 seconds) is how often start_git_watch() reads the repository's state; it reads it after every Git action too, in the background.

The hooks have defaults; override the ones your application does differently:

Hook Default
git_folder() the application's folder
editors(), open_file(path) (async) EditorMixin's when you have it, else the desktop's EditorWindows
git_border_window() the explorer's window: its border shows the branch
explorer_tree() that window's tree: it shows the marks
place_git_window(window), place_git_log(window) insert_window(window); place them along the bottom, for example
show_git_status(state) your application's update_status(), when it has one; state is a git.Status or None
editor_changed(window) cooperative: marks the editor's lines again once the keys pause; extend it with super()

git_offers(feature) and git_commands() say what is offered; git_state is the last Status read.

API: turboframe.ui.git.

Clone this wiki locally